【发布时间】:2021-05-12 22:56:20
【问题描述】:
我有一个查询“详细信息”,如下所示
query details(
$id: ID!
) {
something(id: $id) {
id
itemId
typesId
itemDetails {
id
name
}
typesDetails {
id
name
}
}
}
我已经定义了如下类型
type itemDetails {
id: String,
name: String,
}
type typesDetails {
id: String,
name: String,
}
type something {
id: ID!
itemId: ID
typesId: [ID!]
itemDetails: itemDetails
typesDetails: [typesDetails]
}
在解析器端(graphql)我必须字段解析 itemDetails(使用我从后端收到的 itemId)。此 itemId 可以为 null 或可以具有一些字符串值,例如示例 '1'。
和 typesDetails 以及我从后端收到的 typesId。 typesId 可以是 null 或 id 数组,例如 ['1','2',...]
const resolvers: Resolvers = {
something: {
itemDetails: async(parent, args, { dataSources: { itemsAPI} }) => {
const itemId = get (parent, 'itemId'); //can be null or string value
if(itemId) {
const { data } = await itemsAPI.getItems();
const item = data.filter((item: any) =>
itemId === item.id
); //filter the data whose id is equal to itemId
return {
id: item[0].id,
name: item[0].name,
}
}else { // how to rewrite this else part
return {}:
}
},
typesDetails: async (parent, args, { dataSources: {assetTypesAPI} }) => {
const typesId = get(parent, 'typesId');
if (typesId) {
const allTypes = await typesAPI.getTypes();
const res = typesId.map((id: any) => allTypes.find((d) => d.id === id)); //filter
//allTypes that match typesId
const final = res.map(({id, name}: {id:string, name:string}) => ({id,name}));
//retreive the id and name fields from res array and put it to final array
return final;
} else { // how to rewrite this else part
return [{}];
}
}
}
上面的代码有效。但是如果后端没有返回 itemId 和 typesId,代码看起来很笨拙。
如果后端的 itemId 为空,如果后端的 typesId 为空,我该如何处理 itemDetails 字段的情况。
有人可以帮我解决这个问题吗?谢谢。
【问题讨论】:
标签: javascript reactjs typescript graphql