typescript - 如何在 Apollo Server 中正确键入上下文对象?

标签 typescript apollo-server

我正在使用 apollo server使用 typescript ,我无法在解析器中获取上下文参数以获取 name位于 context 的房产是一个字符串。现在输入为 any我希望将其输入为 string .我还看到 context当我希望它是一个特定的接口(interface)时,参数是任何类型的。无论如何要告诉上下文和它的属性,我希望它是什么类型,而不是它们都被输入为 any ?

const server = new ApolloServer({
  typeDefs: gql`
    type Query {
      test: String
    }
  `,
  resolvers: {
    Query: {
      test(parent: any, args: any, context, info: any) {
        context.name // name is typed as "any" when I'd like it to be typed as "string"
      }
    }
  },
  context() {
    return { 
      name: 'John Doe' 
    }
  }
})
我试图做这样的事情,但这会引发错误。
context<{ name: string }>() {
  return { 
    name: 'John Doe' 
  }
}
我确实通过明确地告诉上下文它需要什么来让它工作,但这种方式似乎有点乏味,因为我必须导入 Context进入每个解析器文件并手动转换。
interface Context {
  name: string
}

const server = new ApolloServer({
  ...
  resolvers: {
    Query: {
      test(parent: any, args: any, context: Context, info: any) {
        context.name // name is typed as "string" here because I used "context: Context" explicitly
      }
    }
  }
  ...
})

最佳答案

如果您是 graphql-code-generator要生成您的类型,您可以在 codegen.yml 中配置上下文类型:

generates:
  src/generated/graphql.ts:
    config:
      contextType: "src/types#Context"
然后定义你的上下文类型:
export interface Context {
  username: string;
}
现在context解析器方法的参数将输入 Context无需导入类型或进行任何其他更改。

关于typescript - 如何在 Apollo Server 中正确键入上下文对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63159116/

相关文章:

node.js - 如何在 Graphql 中删除内省(introspection)查询的身份验证

typescript - 使用私有(private) typescript 时出现错误

ios - 订阅失败错误 WSError(类型 : Starscream. ErrorType.upgradeError 消息 : \"Invalid HTTP upgrade\", 代码 : 400)?

next.js - 在 next.js api 中使用订阅的 Apollo Server 路由 : websockets trouble

javascript - 如何创建基本客户端以通过 websockets 使用 GraphQL 订阅

node.js - 如何将 cookie 从 apollo-server 传递到 apollo-clenet

javascript - TypeScript - 模块在运行时未定义

angular - 两个子组件共享控制权

angular - 您可能需要一个合适的加载器来处理这种文件类型。 typescript

typescript - 为什么我可以在 Typescript 中创建不可能的交集类型?