Junction guide / Hooks
What is on ctx
ctx is the one object every hook and method receives, on every transport. It holds the caller, what was asked for, and a place for a hook's own scratch, and each field has one rule for whether it travels into a nested call.
const app = await createTestApp({ users: [{ id: 'u1', role: 'developer' }] })
const seen: Record<string, unknown> = {}
app.services.register(createService({
name: 'projects',
async find(ctx) {
seen.user = ctx.user?.id
seen.query = ctx.query
seen.limit = ctx.directives.limit
seen.stamp = ctx.locals.stamp
return []
},
hooks: { before: { find: [(ctx) => { ctx.locals.stamp = 'set in before' }] } },
}))
await app.runAs('u1', () => app.service('projects').find({ status: 'open' }, { directives: { limit: 10 } }))
if (seen.user !== 'u1') throw new Error('the principal did not arrive')
if (JSON.stringify(seen.query) !== '{"status":"open"}') throw new Error('query holds more than filters')
if (seen.limit !== 10) throw new Error('the limit is a directive')
if (seen.stamp !== 'set in before') throw new Error('locals did not reach the method')
What else it can do
ctx.useris the principal, frozen, and propagates to nested calls;nullwhen nobody is signed inctx.callerholdsip,userAgentandheaders, and is{}on an in-process callctx.queryis filters only andctx.directivesis{ limit, offset, orderBy, select }; no$key is on eitherctx.datais the payload, a row or an array of rowsctx.routeholds path captures and is{}on an internal call; there is noctx.paramsctx.localsis scratch, fresh for every call and not shared with a nested onectx.transientsandctx.reservedhold the payload and query keys a service set asidectx.resultisnulluntil the method has run; abeforehook may set it to answer earlyctx.signalaborts when the caller leavesctx.afterCommit(fn)andctx.enqueue(job, payload)queue work for after the write- A request handler written with
app.getholds a different context, withctx.jsonandctx.headers
In depth: README ยง 1. The transport bridge โ transport/bridge.ts and docs/internals.md