簡體   English   中英

如何從生成的模式中獲取簡單的 graphql 突變查詢?

[英]How to get simple graphql mutation query from generated schema?

我正在使用 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 }
  })

代碼生成.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

如果我理解正確的話, AddDataDocument是一個DocumentNode object( gql調用的返回值),您希望從中以字符串形式返回查詢。 是嗎?

如果是這樣試試這個:

import { print } from 'graphql'

...

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

幾天前我遇到了類似的問題(問題的“如何將已解析的文檔 object 恢復為字符串”部分)。

這是這個想法的來源:

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

暫無
暫無

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

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