编辑:已添加ARTICLES_QUERY
,tsconfig.json
并package.json
根据要求
编辑2:这有效,但似乎是一个丑陋的解决方案。如果有人有更好的一个,我将不胜感激
export default class InterfaceGraphQLApi extends GraphQLDataSource {
baseURL = "http://localhost:4545/admin/api";
query = super.query;
编辑3:@Max的解决方案解决了查询字段的问题,但由于另一个“错误”,导致TS无法编译源:
ARTICLE_QUERY
这是
const ARTICLE_QUERY = gql`
query Article($id: ID!) {
Article(where: { id: $id }) {
title
text
video {
youtube {
... on OEmbedVideo {
html
type
}
}
}
podcast {
spotify {
... on OEmbedRich {
html
type
}
}
}
images {
file {
filename
}
}
}
}
`;
编辑4:Max的编辑解决方案工作正常。
我是TypeScript的新手。我正在导入一个库,该库允许我为Apollo Server项目定义GraphQL数据源。在我的项目中,我正在扩展该库定义的类
import { GraphQLDataSource } from "apollo-datasource-graphql";
import { gql } from "apollo-server";
const ARTICLES_QUERY = gql`
query {
allArticles {
title
text
id
status
images {
file {
filename
}
}
}
}
`;
export default class InterfaceGraphQLApi extends GraphQLDataSource {
baseURL = "http://localhost:4545/admin/api";
async getArticles() {
try {
const response = await this.query(ARTICLES_QUERY);
但是TypeScript抱怨this.query
说
该query
方法来自导入的库的类。我该如何解决使TypeScript满意?
tsconfig.json是
{
"compilerOptions": {
"target": "ESNext",
"lib": [
"esnext",
"dom"
],
"skipLibCheck": true,
"outDir": "dist",
"strict": false,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"sourceMap": true
},
"exclude": [
"node_modules"
]
}
和package.json是
{
"dependencies": {
"apollo-datasource-graphql": "^1.3.2",
"apollo-server": "^2.10.1",
"graphql": "^14.6.0"
},
"devDependencies": {
"babel-eslint": "^10.0.3",
"eslint": "^6.8.0",
"eslint-config-airbnb-base": "^14.0.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-prettier": "^3.1.2",
"pino": "^5.16.0",
"prettier": "^1.19.1",
"ramda": "^0.26.1",
"typescript": "^3.8.3"
},
"scripts": {
"dev": "tsc && node dist/index.js"
}
}
另外,我想知道是否有人可以引导我实现Apollo Server和GraphQL所需的类型定义-我搜索了“ type definitions Apollo Server”并提出了这个建议,但是它有很多依赖关系也必须找到并下载。我想知道是否有类似的事情@types/apollo-server
(当我这样做的时候yarn @types/apollo-server
,我得到了https://registry.yarnpkg.com/@types%2fapollo-server: Not found.
)。
感谢您提供任何信息!
在apollo-datasource-graphql存储库中有一个开放的PR:https : //github.com/poetic/apollo-datasource-graphql/pull/11
在此期间,有一种解决方案可以为您提供帮助。从以下位置更改导入:
import { GraphQLDataSource } from 'apollo-datasource-graphql';
至
import { GraphQLDataSource } from 'apollo-datasource-graphql/src';
最后,我在研究过程中发现了有趣的部分。我在apollo服务器的文档中找到了一个部分,您可以在其中定义一个api作为资源而不是graphql服务器。在您提供的代码中实际上就是这种情况。
此外,如果还有其他问题可能会阻止tsc进行编译,请在node_modules下进入apollo-datasource-graphql文件夹,然后转到查询功能。options参数有所需的类型。正如文档所说,您需要在选项中提供作为第一个参数传递的查询,就像这样的查询
const response = await this.query(ARTICLE_QUERY, { query: ARTICLE_QUERY, variables: { id }});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句