我不确定自己在做什么错。我无法使用GraphQL来查询这似乎是一个非常简单的API?
https://data.brreg.no/enhetsregisteret/enhet.json
我尝试了不同的解决方案。但是我遇到了相同的错误/问题。
import { ApolloServer, gql, IResolverObject } from "apollo-server";
import fetch from "node-fetch";
const typeDefs = gql`
type Company {
organisasjonsnummer: Int
navn: String
}
type Query {
companies: [Company!]!
}
`;
const resolvers: IResolverObject = {
Query: {
companies: async () => {
const response = await fetch(
"https://data.brreg.no/enhetsregisteret/enhet.json"
);
const data = await response.json();
return data.results;
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers
});
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`);
});
在GraphQL游乐场中使用的查询:
{
companies{
organisasjonsnummer
}
}
从GraphQL Playground收到错误:
{
"errors": [
{
"message": "Cannot return null for non-nullable field Query.companies.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"companies"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: Cannot return null for non-nullable field Query.companies.",
" at completeValue (F:\\apollo-datasource-rest-example\\node_modules\\graphql\\execution\\execute.js:573:13)",
" at F:\\apollo-datasource-rest-example\\node_modules\\graphql\\execution\\execute.js:505:16",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
}
}
],
"data": null
}
答案 0 :(得分:0)
因为从该链接返回的JSON没有一个名为“ results”的字段,所以对于companies
根查询,将解析为null,但是由于其模式定义为[Company!]!
。
您应该根据该链接返回的JSON结构,从此解析器返回data.data
。