我正在使用 nextJS,我希望我的前端对 apollo 的查询做出反应,但没有任何配置在工作。当我使用
import {gql} from src/__generated__/gql
时,我的查询出现未知错误,当我将鼠标悬停在 gql() 上时出现以下消息:
The query argument is unknown! Please regenerate the types
我的问题是我是否需要做一些不同的事情,因为我正在使用 nextJS?我希望能够将 TypeScript 与 Apollo Client 代码 gendocs 一起使用 这样我的 gql 查询将被输入
我的整个 pothos 模式都在我的
pages/api/index.ts
文件中(我还不知道如何将这段代码分散到多个文件中)
示例查询:
const CREATED_EVENT_QUERY = gql(`
query EventById($id: mongoId!) {
eventById(id: $id) {
_id
name
description
location{
coordinates
}
date
eventApplicants{
name
userId
weight
}
link
weights{
weight
spotsAvailable{
name
userId
}
}
}
}
`);
// Apollo Query
const { loading, error, data } = useQuery(CREATED_EVENT_QUERY, {
variables: {
id: params.id
}
});
上面的链接
import { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: 'http://localhost:3000/api',
documents: ['*.ts'],
generates: {
'./src/__generated__/': {
preset: 'client',
plugins: [],
presetConfig: {
gqlTagName: 'gql',
}
}
},
ignoreNoDocuments: true,
};
export default config;
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
// ...
generates: {
'path/to/file.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
config: {
reactApolloVersion: 3
}
}
}
}
export default config
import { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: 'http://localhost:3000/api',
documents: ['*.ts'],
generates: {
'pages/api/index.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
config: {
reactApolloVersion: 3
}
}
},
ignoreNoDocuments: true,
};
export default config;
这假设您的 graphql 服务器位于 api/index.ts
// in the root of your project
import { CodegenConfig } from "@graphql-codegen/cli";
const config: CodegenConfig = {
schema: "http://localhost:3000/api",
documents: ["app/**/*.tsx", "!pages/api/index.ts"],
generates: {
"./src/__generated__/": {
preset: "client",
plugins: [],
presetConfig: {
gqlTagName: "gql",
},
},
},
ignoreNoDocuments: true,
};
export default config;
"scripts": {
"compile": "graphql-codegen",
"watch": "graphql-codegen --w"
},
请注意,您必须更新导入,以便您的 src 文件夹路径正确
import {gql} from "src/__generated__"
除了 Wayne 的解决方案(因为我发现我的配置文件的布局几乎与他的完全相同,除了我没有使用 NextJS 之外)。
每当您更改查询中的任何内容时,例如
const GET_ALL_POSTS = gql(`
query Posts {
posts {
postId
type
content
author {
familyName
givenName
}
}
}
`);
您必须重新运行编译脚本。一旦你这样做了,错误就会消失。
更正,现在我的一些查询有效,而有些则无效,我仍然没有弄清楚这背后的原因