首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Fastify JWT与postgraphile结合使用

将Fastify JWT与postgraphile结合使用
EN

Stack Overflow用户
提问于 2020-04-27 21:53:38
回答 1查看 604关注 0票数 0

我正在尝试用fastify服务器设置postgraphile,它的效果和预期的一样。我怎样才能使fastify-jwt插件与postgraphile一起工作?

下面是我的代码:

installPostgraphile.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
  }
});

任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

发布于 2020-04-28 15:38:02

问题:您正在使用fastify中间件函数fastify.use(postgraphile..

注册为中间件的函数在添加app.authenticate逻辑的preValidation钩子之前执行。

lifecycle doc显示:正如您所看到的,在中间件之前运行的唯一挂钩是onRequest,因此您应该更改:

代码语言:javascript
复制
routeOptions.onRequest = [app.authenticate];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61460492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档