@gis-ag/oniyi-http-plugin-cache-redis
Version:
Plugin responsible for caching responses into redis db
83 lines (64 loc) • 1.92 kB
JavaScript
;
// node core modules
// 3rd party modules
const debug = require('debug')('oniyi-http-plugin:cache:phase-lists:response:parse-context');
// internal modules
const {
updateContext,
} = require('../../utils');
const {
constants: { PHASE_NAME, ERROR_MSG, HOOK_STATE },
} = require('./utils');
const PHASE_NAME_BEFORE = `${PHASE_NAME}:before`;
const parseBeforeCaching = {
phaseName: PHASE_NAME_BEFORE,
handler: (ctx, next) => {
const {
responseError,
response = {},
hookState: { cache: { privateHashedId, evaluator } = {} },
options: { phasesToSkip: { responsePhases = [] } = {} },
} = ctx;
const contextUpdater = updateContext(ctx, debug);
const abortCaching = () => contextUpdater(HOOK_STATE, { cache: { abortCaching: true } });
if (responseError) {
debug(ERROR_MSG);
debug(`Reason: Error occurred in [${PHASE_NAME_BEFORE}] -> \n%O`, responseError);
abortCaching();
next(responseError);
return;
}
if (responsePhases.includes(PHASE_NAME)) {
debug(ERROR_MSG);
debug(`Reason: Phase [${PHASE_NAME}] marked for skipping`);
abortCaching();
next();
return;
}
const isStorable = evaluator.isStorable(response);
const isResponsePrivate = evaluator.private;
if (!isStorable) {
debug(ERROR_MSG, response.headers);
debug('Reason: Provided response is not storable');
abortCaching();
next();
return;
}
// if response is meant to be stored privately, but privateHashedId is missing,
// abort caching.
if (isResponsePrivate && !privateHashedId) {
debug(ERROR_MSG);
debug('Reason: Missing private hashed id');
abortCaching();
next();
return;
}
contextUpdater(HOOK_STATE, {
cache: {
isResponsePrivate,
},
});
next();
},
};
module.exports = parseBeforeCaching;