|
| 1 | +/* @flow */ |
| 2 | +/* eslint-disable no-param-reassign */ |
| 3 | + |
| 4 | +import { ResolverMiddleware, TypeComposer } from 'graphql-compose'; |
| 5 | +import { GraphQLID, GraphQLString, GraphQLObjectType } from 'graphql'; |
| 6 | +import { toGlobalId } from './globalId'; |
| 7 | + |
| 8 | +export class MutationMiddleware extends ResolverMiddleware { |
| 9 | + // constructor(typeComposer, opts = {}) { |
| 10 | + // super(typeComposer, opts); |
| 11 | + // } |
| 12 | + |
| 13 | + args = (next) => (args) => { |
| 14 | + const nextArgs = next(args); |
| 15 | + |
| 16 | + if (!nextArgs.clientMutationId) { |
| 17 | + nextArgs.clientMutationId = { |
| 18 | + type: GraphQLString, |
| 19 | + description: 'The client mutation ID used by clients like Relay to track the mutation. ' |
| 20 | + + 'If given, returned in the response payload of the mutation.', |
| 21 | + }; |
| 22 | + } |
| 23 | + |
| 24 | + return nextArgs; |
| 25 | + }; |
| 26 | + |
| 27 | + |
| 28 | + resolve = (next) => (resolveParams) => { |
| 29 | + let clientMutationId; |
| 30 | + |
| 31 | + if (resolveParams && resolveParams.args && resolveParams.args.input |
| 32 | + && resolveParams.args.input.clientMutationId) { |
| 33 | + clientMutationId = resolveParams.args.input.clientMutationId; |
| 34 | + delete resolveParams.args.input.clientMutationId; |
| 35 | + } |
| 36 | + |
| 37 | + return next(resolveParams) |
| 38 | + .then(res => { |
| 39 | + res.nodeId = toGlobalId( |
| 40 | + this.typeComposer.getTypeName(), |
| 41 | + this.typeComposer.getRecordId(res), |
| 42 | + ); |
| 43 | + if (clientMutationId) { |
| 44 | + res.clientMutationId = clientMutationId; |
| 45 | + } |
| 46 | + return res; |
| 47 | + }); |
| 48 | + }; |
| 49 | + |
| 50 | + |
| 51 | + outputType = (next) => (outputType) => { |
| 52 | + const nextOutputType = next(outputType); |
| 53 | + |
| 54 | + if (!(nextOutputType instanceof GraphQLObjectType)) { |
| 55 | + return nextOutputType; |
| 56 | + } |
| 57 | + |
| 58 | + const outputTC = new TypeComposer(nextOutputType); |
| 59 | + if (!outputTC.hasField('nodeId')) { |
| 60 | + outputTC.addField('nodeId', { |
| 61 | + type: GraphQLID, |
| 62 | + description: 'The globally unique ID among all types', |
| 63 | + }); |
| 64 | + } |
| 65 | + |
| 66 | + if (!outputTC.hasField('clientMutationId')) { |
| 67 | + outputTC.addField('clientMutationId', { |
| 68 | + type: GraphQLString, |
| 69 | + description: 'The client mutation ID used by clients like Relay to track the mutation. ' |
| 70 | + + 'If given, returned in the response payload of the mutation.', |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + return outputTC.getType(); |
| 75 | + }; |
| 76 | +} |
0 commit comments