Session

Custom global state that persists throughout a request's life cycle

yarn add q3-core-session

The session package appears in several places throughout Q3. Most notably, it configures middleware in q3-core-composer for assigning USER to the namespace. Similarly, it registers a global mongoose plugin in q3-api that appends a __$q3 property inside both pre and post schema hooks.

Method

Parameters

Returns

Description

get

String, String, Mixed

Mixed

Get a single value from the context. It works a lot like Lodash's get, so you can query for nested paths and set default return values.

set

String, Mixed

Undefined

Set a single value in the context

nx

String, Mixed/Promise

Mixed

Get or set a value depending on if its exists in the context

getAll

--

Object

Get all values from the context

kill

--

Undefined

Clear all values from the context

intercept

String, Function

Undefined

Dynamically set a value in the context (callback receives the request object)

Example

The example below illustrates how to query the context from within functions outside the scope of your controllers.

const { get, intercept } = require('q3-core-session');
const { getPriceIn } = require('../utils'); 

/**
 * This function executes inside express.
 * It is the last call before the controller.
 */
intercept('CURRENCY', (req) => {
    return req.headers['x-display'];
});

/**
 * This function queries a key set in the intercept callback.
 */
exports.convertPriceToLocalCurrency = async () => {
    const currency = get('CURRENCY');
    return getPriceIn(currency);
};

Last updated