Skip to content

Instantly share code, notes, and snippets.

@KidkArolis
Created June 26, 2020 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KidkArolis/98c5305dfe3c0f259d34cc1061eeb522 to your computer and use it in GitHub Desktop.
Save KidkArolis/98c5305dfe3c0f259d34cc1061eeb522 to your computer and use it in GitHub Desktop.
/*
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
}
}
}
@KidkArolis
Copy link
Author

@bwgjoseph you're right, it could be fixed by readding addParamsForward() hook in after all, so that it uses updated the closed over context when computing forwardedParams.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment