简体   繁体   中英

How to get simple graphql mutation query from generated schema?

I'm using the graphql code generator to get my generated file:

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

In this file I do have

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

which gives me the gql document.

In my tests (using supertest ), I'm doing:

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

I do not want to write the mutation manually. I would like to use my generated schema file. But unfortunatly there is a gql defined, like mentioned at the beginning of this post.

Is it possible to generate something to be used in my 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

If I understood you correctly, AddDataDocument is a DocumentNode object (the return value of the gql invocation) and you want to get back the query as a string from it. Is that it?

If so try this:

import { print } from 'graphql'

...

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

I've faced a similar problem a couple of days ago (the "how do I get the parsed document object back into a string" part of the question).

Here's where the idea came from:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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