我有这样的架构:
type Invoice {
id: ID! @unique
description: String
charge: Charge
}
type Charge {
id: ID! @unique
amount: Float
dataFromAPI: DataFromAPI
}
type DataFromAPI {
id: ID! @unique
status: String
}
在查询解析器中,我有:
async function charge(parent, args, ctx, info) {
chargeData = await ctx.db.query.charge(args, info)
chargeData.dataFromAPI = await DO_THE_API_CALL_TO_RETRIEVE_DATA()
return chargeData
}
和
async function invoice(parent, args, ctx, info) {
invoiceData = await ctx.db.query.invoice(args, info)
return invoiceData
}
查询:
query ChargeQuery {
charge {
id
amount
dataFromAPI
}
}
将返回
{
charge {
id: '232323'
amount: 323
dataFromAPI: 'GREAT! DATA IS FROM API'
}
}
但此查询:
query InvoiceQuery {
invoice {
id
description
charge {
id
amount
dataFromAPI
}
}
}
将返回
{
Invoice {
id: '7723423',
description:'yeah',
charge {
id: '232323'
amount: 323
dataFromAPI: null
}
}
}
dataFromAPI
为空,因为我尚未在此解析器中调用API。
我应该在哪里调用函数DO_THE_API_CALL_TO_RETRIEVE_DATA()
。
在每个解析器中?我想这样做是不可扩展的。
答案 0 :(得分:0)
解决方案是: 我们应该在字段级别上使用解析器。
type Charge {
id: ID!
invoice: Invoice!
messageErrorPayment: String
stripeChargeId: String!
dateErrorPayment: DateTime
createdAt: DateTime!
chargeData: ChargeData
}
const { Query } = require('./Query')
const { Mutation } = require('./mutation/Mutation')
const { Charge } = require('./Charge')
module.exports = {
Query,
Mutation,
Charge,
}
async function chargeData(parent, args, ctx, info) {
return {
dataFromAPI: await DO_THE_API_CALL_TO_RETRIEVE_DATA()
}
}
const Charge = {
chargeData,
}
module.exports = {
Charge,
}