Petro Ivanenko
Petro Ivanenko

Reputation: 727

Return custom field based on other not requested field?

Let's say that I want to get a person's age using this query:

{
  getUser(id: "09d14db4-be1a-49d4-a0bd-6b46cc1ceabb") {
    full_name
    age
  }
}

I resolve my getUser query like this (I use node.js, type-graphql and knex):

async getUser(getUserArgs: GetUserArgs, fields: UserFields[]): Promise<User> {
  // Return ONLY ASKED FIELDS
  const response = await knex.select(this.getKnexFields(fields)).from(USER).whereRaw('id = ?', [getUserArgs.id]);
  // returns { full_name: 'John Smith' }
  return response[0];
}

The problem is that then I can't calculate age field, because I did not get born_at (datetime field stored in a db) in the first place:

@FieldResolver()
age(@Root() user: User, @Info() info: GraphQLResolveInfo): number {
  console.log(user); // { full_name: 'John Smith' }  no born_at field - no age, so error
  // calculate age from born_at
  return DateTime.fromJSDate(user.born_at).diff(DateTime.fromJSDate(new Date()), ['years']).years;
}

Is there some fancy graphql-build-in way / convention to predict that born_at will be needed instead of doing it manually through info / context?

Upvotes: 0

Views: 606

Answers (1)

Michał Lytek
Michał Lytek

Reputation: 12087

You should always return full entity data from the query-level resolvers, so they are available for field resolvers.

The other solution is to manually maintain a list of required fields for field resolvers, so your "fields to knex" layer can always include them additionally".

Further improvements might be to can a list of additional columns based on the requested fields (thus the field resolvers that will be triggered).

Upvotes: 1

Related Questions