【问题标题】:GraphQL - Prisma - resolvers using external APIGraphQL - Prisma - 使用外部 API 的解析器
【发布时间】:2019-06-19 19:13:24
【问题描述】:

我有这个架构:

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

【问题讨论】:

    标签: graphql resolver prisma


    【解决方案1】:

    解决办法是: 我们应该在字段级别使用解析器。

    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

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2019-12-18
      • 2019-12-12
      • 2018-11-19
      • 2018-03-26
      • 2019-10-24
      • 2021-03-10
      • 2019-06-13
      • 2020-05-10
      相关资源
      最近更新 更多