0

Is it possible to add a look up to a mutation in GraphQL? Let's say something like an input type where one property is the result of another query.

createPerson(name: "Steve", gender: genders ( name: { eq: "mail" } ) { id } )

where genders ( name: { eq: "mail" } ) { id } would return exactly one result value

xadm
  • 8,219
  • 3
  • 14
  • 25
Sascha
  • 10,231
  • 4
  • 41
  • 65
  • [almost] everything is possible... [ time and money limits ]... if supported by mutation resolver ... if not, simply query before mutation (2 requests) – xadm May 14 '20 at 14:57
  • I am trying to prefill a database and must query the keys of another table. I'd like to have this all in one file for the customer to be able to execute it – Sascha May 15 '20 at 05:42
  • 1
    you don't need it at all ... just write an resolver for user\gender [query], it will be called when main user resolver won't read gender field ... in this resolver read other table, update user record and return value - next time value will be read with all user fields, gender resolver won't be called – xadm May 15 '20 at 09:56
  • This is not possible since it violates the GraphQL spec. Inputs are considered raw data so you cannot fill them with another field from your type. – Michael Ingmar Staib Jun 23 '20 at 11:34
  • @xadm Please post your comment as an answer, I'll accept then – Sascha Jul 27 '21 at 09:12

1 Answers1

0

GraphQL allows you to:

  • "get what you want";
  • manipulate data on write;
  • customize response on read;

You can of course write a createPerson mutation resolver to:

  • ask another table for additional data (if missing arg);
  • write into DB;

But it doesn't affect (isn't suitable for) existing records.

You can also use read resolvers to update missing fields in records using field resolver - a kind of 'eventual consistency'.

Write person resolver to read a person record and additional person.gender field resolver to get value for missing gender value. The second one can be used to update the 'main' person [DB table] record:

  • read a missing value from other table;
  • write a value into person record on the 'main' table;
  • return value.

Next time person resolver will read gender value at once (from 'main' person table), [additional] field resolver won't be called at all.

This technique can be used to convert DB data without writing SQL/DB specific code (different syntax/types problems, safer on more complex logic) - it's enough to read each/all person's gender fields. Field resolver (and the other/old table) can be removed after that.

xadm
  • 8,219
  • 3
  • 14
  • 25