Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API: Fix for function based context to run on each request #770

Merged
merged 2 commits into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/api/src/__tests__/graphql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,23 @@ describe('graphql createContextHandler', () => {
callbackWaitsForEmptyEventLoop: false,
})
})
it('also accepts a promise that resolve dynamic value on each run', async () => {
const handler = createContextHandler(async ({ context }) => {
return Promise.resolve({ c: context.d * 5 })
})
// @ts-ignore
expect(await handler({ context: { d: 4 } })).toEqual({
c: 20,
d: 4,
callbackWaitsForEmptyEventLoop: false,
})
// now run same handler again to simulate second request
// with different event and context
// @ts-ignore
expect(await handler({ context: { d: 5 } })).toEqual({
c: 25,
d: 5,
callbackWaitsForEmptyEventLoop: false,
})
})
})
11 changes: 8 additions & 3 deletions packages/api/src/functions/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,17 @@ export const createContextHandler = (
: authToken
}

// Sets the **global** context object, which can be imported with:
// import { context } from '@redwoodjs/api'
if (typeof userContext === 'function') {
userContext = await userContext({ event, context })
// if userContext is a function, run that and return just the result
const userContextData = await userContext({ event, context })
return setContext({
...context,
...userContextData,
})
}

// Sets the **global** context object, which can be imported with:
// import { context } from '@redwoodjs/api'
return setContext({
...context,
...userContext,
Expand Down