当尝试使用graphql-codegen从Prismic生成类型时,出现以下错误:
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网址,则会得到graphiql编辑器。如果我在Postman中访问url,则会收到missing query parameter
(这是预期的)错误,因此该路径似乎在这些环境中有效。我需要与Prismic一起使用的特定配置吗?
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
答案 0 :(得分:1)
我对这个工具不是很熟悉,但是我想默认情况下,这个工具会尝试使用POST方法来调用graphQL API。 由于缓存的原因,Prismic现在仅使用GET,因此我很确定它与此有关。 希望它能帮助您解决问题。
答案 1 :(得分:1)
这确实是因为Prismic GraphQL API使用GET而不是POST请求。我实际上没有找到任何工具可以使用GET自检GraphQL端点。经过一番挖掘之后,提出了以下解决方案:
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),
})
}
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
: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
也许这不是最优雅的解决方案,但它可行!
答案 2 :(得分:1)
这有几个要素:
GET
Prismic-ref
标头必须与 master
引用的 ID 一起传递Codegen 支持 customFetch
选项,允许我们自定义传出请求。我已将上述步骤打包到 customFetch
实现中并在此处发布: