Skip to content
This repository has been archived by the owner on Mar 20, 2023. It is now read-only.

Commit

Permalink
feature(dynamic-context): Execute function for context
Browse files Browse the repository at this point in the history
Provides the ability to do post-AST validation (e.g. security) as well as to build the context dynamically with a user object or other information.
Prettify and test fix
added test for context function support
  • Loading branch information
matthewerwin committed Sep 14, 2017
1 parent 6fc7baf commit 8dc4bdf
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 14 deletions.
31 changes: 31 additions & 0 deletions src/__tests__/http-test.js
Expand Up @@ -1903,5 +1903,36 @@ describe('test harness', () => {
);
});
});

describe('Custom context capabiility', () => {
it('allows context to be a function', async () => {
const app = server();

get(
app,
urlString(),
graphqlHTTP({
schema: TestSchema,
context: () => Promise.resolve('testValue'),
}),
);

const response = await request(app).get(
urlString({
operationName: 'TestQuery',
query: `
query TestQuery { context }
`,
}),
);

expect(response.status).to.equal(200);
expect(JSON.parse(response.text)).to.deep.equal({
data: {
context: 'testValue',
},
});
});
});
});
});
52 changes: 38 additions & 14 deletions src/index.js
Expand Up @@ -247,21 +247,45 @@ function graphqlHTTP(options: Options): Middleware {
);
}
}
// Perform the execution, reporting any errors creating the context.
try {
return execute(
schema,
documentAST,
rootValue,
context,
variables,
operationName,
);
} catch (contextError) {
// Return 400: Bad Request if any execution context errors exist.
response.statusCode = 400;
return { errors: [contextError] };

let preExecute;
if (typeof context === 'function') {
preExecute = Promise.resolve()
.then(() =>
context(
request,
response,
schema,
documentAST,
variables,
operationName,
),
)
.catch(error => {
// If an error was caught, report the httpError status, or 500.
response.statusCode = error.status || 500;
return { errors: [error] };
});
} else {
preExecute = Promise.resolve(context);
}
// Perform the execution, reporting any errors creating the context.
return preExecute
.then(dynamicContext => {
return execute(
schema,
documentAST,
rootValue,
dynamicContext,
variables,
operationName,
);
})
.catch(contextError => {
// Return 400: Bad Request if any execution context errors exist.
response.statusCode = 400;
return { errors: [contextError] };
});
})
.then(result => {
// Collect and apply any metadata extensions if a function was provided.
Expand Down

0 comments on commit 8dc4bdf

Please sign in to comment.