Search code examples
graphqlhotchocolate

GraphQL mutation with subquery for parameter - update/convert DB on write?


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


Solution

  • 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.