Previously I was using apollo-server-express and I wanted to migrate to fastify so I change it to apollo-server-fastify. But it started giving lots of issues.
One of such issue is - Not able to access res object from context function.
Below code was working perfectly but res object itself was not available with apollo-server-fastify
context: async ({ req, res, connection }) => {
// res <--------- undefined
if (connection) {
return {
models,
}
}
if (req) {
const me = await getMe(req, res)
return {
models,
me,
secret: process.env.SECRET,
}
}
},
Yeah, the same issue but you can pass reply instance manually.
File plugins/fastify-apollo-server/index.js
const fp = require('fastify-plugin');
const {ApolloServer} = require('apollo-server-fastify');
// **** Plugin: plugins/fastify-apollo-server/index.js
module.exports = fp(async ( fastify, opts, next ) => {
const server = new ApolloServer({
/* ... */
context: async request => {
const {reply} = request;
return {
request,
reply, // res: reply,
app: fastify,
};
},
});
fastify.addHook('preHandler', async ( request, reply ) => {
if ( String(request.req.url).startsWith('/graphql') ) {
request.reply = reply;
}
});
fastify.register(server.createHandler());
next();
}, {
name: 'fastify-apollo-server',
});
File: init-server.js
const app = require('fastify')();
// Plugins
app.register(require('plugins/fastify-apollo-server'));
(async function () {
await app.listen(3000);
})();
@blacksmoke26 seems like kind of hack, but thats simplest solution as well.
Seems at least somewhat related to https://github.com/apollographql/apollo-server/issues/2476.
@abernix unfortunately, they're unrelated. If you look at the context param then it's documented that fastify receives nothing in the context... (which is inaccurate, it actually receives the req as context.
The linked issue is about express and what its context consists of.
I've been having the same issue and was able to track down the cause. Should have a bug-fix PR up shortly, I'll be sure to link this issue. Meanwhile, if you'd like to check out the fix here it is -> https://github.com/autotelic/apollo-server/pull/1
Any update on this one?
Waiting on #3895 to be merged. Planning to use it to set (JWT) authentication cookies.
Would be great to see this merged! 🙂
Most helpful comment
Yeah, the same issue but you can pass
replyinstance manually.File
plugins/fastify-apollo-server/index.jsFile:
init-server.js