简体   繁体   English

如何在graphql中使用中间件

[英]How to use middleware in graphql

My goal is to use winston ( which is a logging program ).我的目标是使用winston (这是一个日志程序)。 Over time, I will add others middleware, inshallah随着时间的推移,我会添加其他中间件,inshallah

Here is my code ( index.js | main js file ):这是我的代码( index.js | 主 js 文件):

import { ApolloServer } from "apollo-server";
import { typeDefs } from "./graphql/typeDefs/typeDefs";
import { resolvers } from "./graphql/resolvers/resolvers";

const server = new ApolloServer({ typeDefs, resolvers,
  csrfPrevention: true, 
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

package.json package.json

  "devDependencies": {
    "typescript": "^4.8.2"
  },
  "dependencies": {
    "apollo-server": "^3.10.2",
    "winston": "^3.8.1"
  }

console.log(more_info?.more_info.name:'') The data probably isn't ready yet. console.log(more_info?.more_info.name:'')数据可能还没有准备好。 But the way you have asked the question is not very suitable please add code next time through the editor not screenshots so that people can answer easily.但是你提问的方式不是很合适,请下次通过编辑器添加代码而不是截图,以便人们轻松回答。

I found the resource useful.我发现该资源很有用。 However, I noticed that the main function of this resource code wasn't being called, so I used the Immediately-invoked Function Expression (IIFE) method to call it and it worked as intended.但是,我注意到这个资源代码的主要 function 没有被调用,所以我使用了立即调用的 Function 表达式 (IIFE) 方法来调用它,它按预期工作。

my code:我的代码:

(async function startApolloServer(typeDefs, resolvers) {
  const app = express();

  app.use(morgan("combined"));
  // app.use(helmet());

  const httpServer = http.createServer(app);

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    csrfPrevention: true,
    cache: "bounded",
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),
    ],
  });

  await server.start();
  server.applyMiddleware({ app, path: "/" });

  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve)
  );
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
})(typeDefs, resolvers);

winston TS error:温斯顿 TS 错误:

When I try to use the array of levels as mentioned on the docs in the level property of winston.createLogger function, I get a TS error.当我尝试使用 winston.createLogger function 的 level 属性中的文档中提到的级别数组时,出现 TS 错误。 Therefore, I made a small change to the node modules因此,我对节点模块做了一个小改动

代码 文件位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM