我正在尝试用fastify服务器设置postgraphile,它的效果和预期的一样。我怎样才能使fastify-jwt插件与postgraphile一起工作?
下面是我的代码:
installPostgraphile.js
const { postgraphile } = require('postgraphile');
const PgSimplifyInflectorPlugin = require('@graphile-contrib/pg-simplify-inflector');
module.exports = async function (fastify) {
fastify.log.info('Establishing PostgreSQL DB connection...');
await fastify
.use(
postgraphile(
'postgres://postgres:postgres@localhost:5432/demo',
'app_public',
{
dynamicJson: true,
appendPlugins: [PgSimplifyInflectorPlugin],
enhanceGraphiql: process.env.NODE_ENV !== 'production' ? true : false,
graphileBuildOptions: {
nestedMutationsSimpleFieldNames: true,
nestedMutationsDeleteOthers: false,
},
disableQueryLog: process.env.NODE_ENV !== 'production' ? true : false,
graphiql: process.env.NODE_ENV !== 'production' ? true : false,
watchPg: process.env.NODE_ENV !== 'production' ? true : false,
}
)
)
.ready((err) => {
if (err) return fastify.log.error(err);
});
};server.js
const Fastify = require('fastify');
const helmet = require('fastify-helmet');
const cors = require('fastify-cors');
const JWT = require('fastify-jwt');
const fp = require('fastify-plugin');
const installPostgraphile = require('./installPostgraphile');
const app = Fastify({
logger: true,
});
// Register Plugins
app.register(cors);
app.register(helmet);
app.register(JWT, {
secret: 'supersecret',
});
app.post('/login', (req, reply) => {
// some code to authenticate
const token = instance.jwt.sign({ payload: { user: 'foo' } });
reply.send(token);
});
app.decorate('authenticate', async function (request, reply) {
try {
// Autorization logic
await request.jwtVerify();
} catch (err) {
reply.send(err);
}
});
app.addHook('onRoute', (routeOptions) => {
if (routeOptions.url === '/graphql') {
routeOptions.preValidation = [app.authenticate];
}
});
app.register(fp(installPostgraphile));
app.listen(process.env.PORT || 3000, (err) => {
if (err) {
app.log.error(err);
process.exit(1);
}
});任何帮助都是非常感谢的。
发布于 2020-04-28 15:38:02
问题:您正在使用fastify中间件函数fastify.use(postgraphile..。
注册为中间件的函数在添加app.authenticate逻辑的preValidation钩子之前执行。
lifecycle doc显示:正如您所看到的,在中间件之前运行的唯一挂钩是onRequest,因此您应该更改:
routeOptions.onRequest = [app.authenticate];https://stackoverflow.com/questions/61460492
复制相似问题