-
-
Save bwgjoseph/22e848f9e53417350597e2377d20bcc6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Install this hook in app.hooks.js | |
module.exports = app => { | |
app.hooks({ | |
before: { | |
all: [ | |
addParamsForward() | |
] | |
} | |
}) | |
} | |
Then use whenever you want to forward params, e.g. in a hook: | |
const { app, params } = context | |
app.service('another-service').find({ query: { id: 'x' }, ...params.forward() }) | |
app.service('another-service').get(id, params.forward()) | |
app.service('another-service').patch(id, {smth: 'x' }, params.forward()) | |
*/ | |
const { has } = require('lodash') | |
const paramsSeen = new WeakSet() | |
module.exports = function addParamsForward() { | |
return context => { | |
if (paramsSeen.has(context.params)) { | |
throw new Error( | |
`Params should never be shared across services, always use params.forward(). Fix calls to ${context.path}#${context.method}`, | |
) | |
} | |
paramsSeen.add(context.params) | |
context.params.forward = ({ only, omit = [] } = {}) => { | |
const { params } = context | |
const forwardedParams = { | |
caller: { | |
path: context.path, | |
method: context.method, | |
type: context.type, | |
}, | |
requestId: context.params.requestId, | |
forwarded: true, | |
} | |
;( | |
only || [ | |
'authenticated', | |
'user', | |
'transaction', | |
'skipEvents', | |
'permissions', | |
] | |
).forEach(param => { | |
if (has(params, param) && !omit.includes(param)) { | |
forwardedParams[param] = params[param] | |
} | |
}) | |
if (forwardedParams.authenticated) { | |
forwardedParams.authentication = params.authentication | |
} | |
return forwardedParams | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment