【发布时间】:2023-03-12 01:56:02
【问题描述】:
我正在尝试通过调用 api 并在查询中设置参数来获取特定项目。我正在尝试使用 find 功能,但在解决 graphiql 中的查询时出现错误。
这是我用 promise 调用的 api 函数。
var request = require('request');
var options = { method: 'GET',
url: 'myurl',
qs: { searchCriteria: '' },
headers:
{ 'postman-token': '12d2dbd7-6ea1-194c-ad38-5bffbac6706c',
'cache-control': 'no-cache',
authorization: 'Bearer b0kk2w8ptk9smhnl4ogh4y40adly0s5h',
'content-type': 'application/json' } };
const getAllLinks = () => {
return new Promise((resolve, reject) => {
request(options, function (error, response, body) {
//console.log(body);
if (error) {
reject(error);
}
else {
const myJSON = JSON.parse(body);
resolve(myJSON.items);
//console.log(myJSON.items);
}
});
});
};
const testAllLinks = () => {
return getAllLinks().then((res) => {
return res;
})
};
然后在这里我的解析器,查询应该从 api 返回所有项目的特定 id。
Query: {
allItems: (_, { id }) => find(getAllLinks(), {id: id}),
但我不断收到错误 Cannot return null for non-nullable field Query.allItems. 我允许架构中的参数 (allItems(id: Int): [Item]!)。
当我将解析器中的查询更改为:
allItems: () => getAllLinks(), //or testAllLinks() 它返回所有项目。
在这里,我使用查找功能 https://launchpad.graphql.com/r9wk3kpk8n 为这个示例创建了启动板,它在那里工作,但不是在这里......
架构:
const typeDefs = `
type Item {
id: ID!
sku: String!
name: String!
attribute_set_id: Int!
price: Float
status: Int!
visibility: Int!
type_id: String!
created_at: String!
updated_at: String!
product_links: [String]
tier_prices: [Int]
custom_attributes: [CUSTOM_ATTRIBUTES]
}
union CUSTOM_ATTRIBUTES = CustomString | CustomArray
type CustomString {
attribute_code: String
value: String
}
type CustomArray {
attribute_code: String
value: [String]
}
type Query {
allItems(id: Int): [Item]!
}
`;
【问题讨论】:
标签: javascript node.js graphql