GraphQL-Prisma-使用外部API的解析器

时间:2019-01-25 23:05:51

标签: graphql resolver prisma

我有这样的架构:

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()。 在每个解析器中?我想这样做是不可扩展的。

1 个答案:

答案 0 :(得分:0)

解决方案是: 我们应该在字段级别上使用解析器。

schema.graphql

type Charge {
  id: ID!
  invoice: Invoice!
  messageErrorPayment: String
  stripeChargeId: String!
  dateErrorPayment: DateTime
  createdAt: DateTime!
  chargeData: ChargeData
}

/resolvers/index.js

const { Query } = require('./Query')
const { Mutation } = require('./mutation/Mutation')
const { Charge } = require('./Charge')

module.exports = {
  Query,
  Mutation,
  Charge,
}

charge.js

async function chargeData(parent, args, ctx, info) {
  return {
    dataFromAPI: await DO_THE_API_CALL_TO_RETRIEVE_DATA()
  }
}

const Charge = {
  chargeData,
}

module.exports = {
  Charge,
}

来源:https://www.prisma.io/forum/t/how-to-use-field-resolvers-to-get-aggregates-of-inner-relation-types/2930/2?u=alan345