Skip to content

Resolve data from parent fields #301

Closed
@robrichard

Description

@robrichard

The resolve callback on a GraphQL field gets invoked with "root" as the first argument, which can be used to calculate the data for the field. Is there anyway to use data from a parent object to compute a field?

Take this example:

This returned from the underlying api

[
  {
    "id": 123,
    "buyer": {
      "id": 234,
      "preferredCurrency": "EUR"
    },
    "item": {
      "title": "item title",
      "price": {
        "convertedAmounts": {
          "USD": 100,
          "EUR": 90,
          "GBP": 80
        }
      }
    },
    ... 
  }
]

I'd like to write a query like this:

{
  item {
    price {
      buyerPreferredAmount {
        amount
        currency
      }
    }
  }
}

Which returns:

[
  {
    "item": {
        "price": {
          "buyerPreferredAmount": {
            "amount": 90,
            "currency": "EUR"
          }
        }
    }
  }
]

Where the schema is defined like this:

const CurrencyAmount = new graphql.GraphQLObjectType({
  name: 'CurrencyAmount',
  fields: {
    amount: {type: graphql.GraphQLFloat},
    currency: {type: graphql.GraphQLString},
  }
});

const FinancialAmount = new graphql.GraphQLObjectType({
  name: "FinancialAmount",
  fields: {
    buyerPreferredAmount: {
      type: CurrencyAmount,
      resolve(root, args, info) {
         // How can I do something like this?
         // const buyerCurrency = parent.parent.parent.buyer.preferredCurrency 
         return { currency: buyerCurrency, amount: root.convertedAmounts[buyerCurrency] };
      }
    }
  }
});

const Item = new graphql.GraphQLObjectType({
  name: "Item",
  fields: {
    price: {type: FinancialAmount}
  }
});

const Order = new graphql.GraphQLObjectType({
  name: "Order",
  fields: {
    item: {type: Item}
  }
});

How can I implement the resolve method of the buyerCurrency field on FinancialAmount?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions