首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自棱镜的graphql-codegen错误响应

来自棱镜的graphql-codegen错误响应
EN

Stack Overflow用户
提问于 2019-11-12 16:32:15
回答 3查看 917关注 0票数 0

当尝试使用graphql-codegen从棱镜生成类型时,我得到了以下错误:

代码语言:javascript
复制
graphql/types.tsx
    Failed to load schema from [object Object]:

        invalid json response body at https://my-project-name.prismic.io/graphql reason: Unexpected t
oken < in JSON at position 0

我猜它似乎是在返回HTML语言(因此使用了<)。如果我进入Chrome中的graphql url,我会得到graphiql编辑器。如果我转到Postman中的url,我会得到missing query parameter(这是意料之中的)错误,因此路径似乎可以在这些环境中工作。有没有什么特别的配置我需要用在三棱镜上?

代码语言:javascript
复制
schema:
  - https://my-project-name.prismic.io/graphql:
    headers:
      Prismic-Ref: PRISMIC_REF
documents:
  - "graphql/**/*.ts"
generates:
  graphql/types.tsx:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"
    config:
      noHOC: true
      noComponents: true
      noNamespaces: true
      withHooks: true
EN

回答 3

Stack Overflow用户

发布于 2019-11-15 01:11:38

我对这个工具不是很熟悉,但我猜在默认情况下,这个工具会尝试使用POST方法调用graphQL应用程序接口。因为缓存的原因,Prismic现在只使用GET,所以我很确定这与它有关。希望它能帮你找出答案。

票数 1
EN

Stack Overflow用户

发布于 2020-03-06 00:19:01

这确实是因为棱镜GraphQL应用编程接口使用GET而不是POST请求。实际上,我没有找到任何可以使用GET内省GraphQL端点的工具。经过一小段时间的挖掘,得出了以下解决方案:

  1. 此代码基于prismic-apollo-link。我稍微修改了一下,因为我要将它与Next JS结合使用(我需要同构的unfetch)。如果你没有使用Next JS,你仍然需要它,因为我们需要fetch才能在Node中工作。

代码语言:javascript
复制
import {ApolloClient} from 'apollo-client'
import {InMemoryCache} from 'apollo-cache-inmemory'
import {HttpLink} from 'apollo-link-http'
import {setContext} from 'apollo-link-context'
import Prismic from 'prismic-javascript'
import fetch from 'isomorphic-unfetch'

const baseEndpoint = 'https://<your project>.cdn.prismic.io'
const accessToken = '<your access token>'

export default function createApolloClient(initialState, ctx) {
  const primicClient = Prismic.client(`${baseEndpoint}/api`, {accessToken})

  const prismicLink = setContext((req, options) => {
    return primicClient.getApi().then(api => ({
      headers: {
        'Prismic-ref': api.masterRef.ref,
        ...options.headers,
        ...((api as any).integrationFieldRef
          ? {'Prismic-integration-field-ref': (api as any).integrationFieldRef}
          : {}),
        ...(accessToken ? {Authorization: `Token ${accessToken}`} : {}),
      },
    }))
  })

  const httpLink = new HttpLink({
    uri: `${baseEndpoint}/graphql`,
    useGETForQueries: true,
    fetch,
  })

  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: prismicLink.concat(httpLink),
    cache: new InMemoryCache().restore(initialState),
  })
}

  1. 创建一个脚本来内省棱镜GraphQL服务器:

代码语言:javascript
复制
import createApolloClient from '../apolloClient'
import gql from 'graphql-tag'
import path from 'path'
import fs from 'fs'

const client = createApolloClient({}, null)

const main = async () => {
  try {
    const res = await client.query({
      query: gql`
        query IntrospectionQuery {
          __schema {
            queryType {
              name
            }
            mutationType {
              name
            }
            subscriptionType {
              name
            }
            types {
              ...FullType
            }
            directives {
              name
              description
              locations
              args {
                ...InputValue
              }
            }
          }
        }

        fragment FullType on __Type {
          kind
          name
          description
          fields(includeDeprecated: true) {
            name
            description
            args {
              ...InputValue
            }
            type {
              ...TypeRef
            }
            isDeprecated
            deprecationReason
          }
          inputFields {
            ...InputValue
          }
          interfaces {
            ...TypeRef
          }
          enumValues(includeDeprecated: true) {
            name
            description
            isDeprecated
            deprecationReason
          }
          possibleTypes {
            ...TypeRef
          }
        }

        fragment InputValue on __InputValue {
          name
          description
          type {
            ...TypeRef
          }
          defaultValue
        }

        fragment TypeRef on __Type {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                  ofType {
                    kind
                    name
                    ofType {
                      kind
                      name
                      ofType {
                        kind
                        name
                      }
                    }
                  }
                }
              }
            }
          }
        }
      `,
    })

    if (res.data) {
      const schema = JSON.stringify(res.data)
      // Specify where the schema should be written to
      fs.writeFileSync(path.resolve(__dirname, '../../schema.json'), schema)
    } else {
      throw new Error('No Data')
    }
    process.exit()
  } catch (e) {
    console.log(e)
    process.exit(1)
  }
}

main()

在您的codegen.yml中包含脚本

代码语言:javascript
复制
schema: "./schema.json"
documents: ./src/**/*.graphql
generates:
  ./src/generated.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      withHooks: true
      withComponent: false
hooks:
  afterStart:
    - ts-node  <path to script>/introspectPrismic.ts

也许这不是最优雅的解决方案,但它是有效的!

票数 1
EN

Stack Overflow用户

发布于 2021-01-27 04:30:06

这里面有几个元素:

即使对于introspection,

  • 请求也必须使用
  • Prismic-ref请求必须使用master ref
  • 的ID传递,必须提供访问令牌(对于私有API)

Codegen支持customFetch选项,允许我们定制传出请求。我已经将上面的步骤打包到一个customFetch实现中,并在这里发布:

https://www.npmjs.com/package/codegen-prismic-fetch

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58814765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档