【问题标题】:How to get simple graphql mutation query from generated schema?如何从生成的模式中获取简单的 graphql 变异查询?
【发布时间】:2020-12-19 23:49:09
【问题描述】:

我正在使用 graphql 代码生成器来获取我生成的文件:

npx graphql-codegen --config libs/codegen.yml

在这个文件中我确实有

export const AddDataDocument = gql`
    mutation addData($input: AddDataInput!) {
    addData(input: $input) {
        id
    }
}`;

这给了我 gql 文档。

在我的测试中(使用supertest),我正在做:

const query = `
    mutation addData($input: AddDataInput!) {
    addData(input: $input) {
        id
    }
}`
request(app.getHttpServer())
  .post('/graphql')
  .send({
    operationName: null,
    query,
    variables: { input: addDataInput }
  })

我不想手动编写突变。我想使用我生成的模式文件。但不幸的是,定义了一个 gql,就像本文开头提到的那样。

是否可以生成一些东西在我的send() 中使用?

request(app.getHttpServer())
  .post('/graphql')
  .send({
    operationName: null,
    query: AddDataDocument, // <-- but this is not working as it is a gql document
    variables: { input: addDataInput }
  })

codegen.yml

overwrite: true
schema: "apps/backend/src/app/**/*.graphql"
generates:
libs/generated/generated.ts:
    documents: "libs/**/*.graphql"
    plugins:
    - "typescript"
    - "typescript-operations"
    - "typescript-react-apollo"
    config:
    withHooks: true
    withComponent: false
    withHOC: false

【问题讨论】:

    标签: javascript graphql supertest graphql-codegen


    【解决方案1】:

    如果我的理解正确,AddDataDocument 是一个DocumentNode 对象(gql 调用的返回值),并且您希望从中获取作为字符串的查询。是这样吗?

    如果是这样试试这个:

    import { print } from 'graphql'
    
    ...
    
    request(app.getHttpServer())
      .post('/graphql')
      .send({
        operationName: null,
        query: print(AddDataDocument),
        variables: { input: addDataInput }
      })
    

    几天前我遇到了类似的问题(问题的“如何将已解析的文档对象重新转换为字符串”部分)。

    这个想法是从哪里来的:

    https://github.com/apollographql/graphql-tag/issues/144

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2019-10-23
      • 2020-12-05
      • 2021-10-03
      • 2019-05-02
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2018-06-07
      相关资源
      最近更新 更多