簡體   English   中英

如何在不重新創建請求處理程序的情況下更改或擴展 express-graphql 上下文?

[英]How to change or extend express-graphql context without recreating the request handler?

如何在不重新創建請求處理程序的情況下更改/擴展 express-graphql 上下文?

/** */
const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});
/** */
export default (req: any, res: any, context: any) => {
  console.log("context:", context);
  const handler = graphqlHTTP({
    schema,
    graphiql: process.env.NODE_ENV !== "production",
    context: {
      req,
      ...context,
    },
  });  
  return handler(req, res);
};

我注意到 graphqlHTTP 接受 promise 作為選項。
不知道這有什么幫助。 因為(req)=> Promise<Otions> (options-callback) 無論如何都需要為每個請求重新構建?
我錯過了什么?

注意:請忽略上下文構建實現,它可以是你喜歡的任何東西

這似乎可以解決問題,部分...

/** */
const handler = graphqlHTTP(async (req: any) => {  
  return {
    schema,
    graphiql: process.env.NODE_ENV !== "production",
    /** this doesn't work */
    context: {
      req,
      session: await getSession({ req }),
    },
  };
});

但是所有上下文依賴項都需要預先聲明。 重建回調將需要構建處理程序。

謝謝

鑒於缺乏反饋......我不確定我是否在問一些“明顯”或明顯錯誤的東西:)。

但是,......無論如何,這是我找到的最接近的

/** */
const handler = graphqlHTTP(async (req) => {  
  return {
    schema,
    graphiql: process.env.NODE_ENV !== "production",
    /** this doesn't work */
    context: {
      req,
      session: await getSession({ req }),
    },
  };
});

...仍然,讓您獨自通過外部方式構建自己的依賴關系圖,例如動態導入、需求、依賴注入、單例、HOC...等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM