Queries & Mutations
18 min
A query reads data; a mutation changes it — but in GraphQL,
both shapes look similar: you send a request, and get back exactly the
fields you asked for. A mutation just also applies some change first.
This means a client can update a record and immediately see the
resulting fields it cares about, all in one round trip, using the exact
same resolve selection logic from the previous module.
def apply_mutation(data, updates, query):
updated = dict(data)
updated.update(updates)
return resolve(query, updated)
The original 'user' dict itself is never mutated in place -- apply_mutation builds a NEW dict via dict(data) then .update(updates), the same immutable-update discipline from Functional Programming's pure-functions module, applied here so the caller's original data stays untouched.
Using the provided `resolve`, write `apply_mutation(data, updates, query)`: apply `updates` (a dict of field changes) on top of `data`, then return only the fields requested by `query` from the UPDATED object.
Why does a GraphQL mutation still specify a field-selection query, exactly like a read-only query does?
You can implement a mutation that applies a change and returns exactly the requested fields of the result in one step, the same selective-response idea queries use.