import { DocumentNode , GraphQLError } from 'graphql' ; import { MutationOptions } from 'apollo-client' ; import { FetchResult } from 'apollo-link' ; import { MutationDef , MutationObject } from './types/mutation' ; import { Store } from './internal/store' ; import { getMutationDefinition , getFirstField } from './internal/utils' ; import { Manager } from './manager' ; import { buildContext , buildGetCacheKey } from './helpers' ; export class MutationManager extends Store < MutationDef > { constructor ( defs ? ) { super ( ) ; if ( defs ) { defs . forEach ( def => { this . set ( def . mutation , def ) ; } ) ; } } add ( defs ) { defs . forEach ( def => { this . set ( def . mutation , def ) ; } ) ; } } export function mutationToType ( action ) { const mutation = getMutation ( action ) ; const name = getNameOfMutation ( mutation ) ; return name ; } export function getMutation ( action ) { if ( action . constructor && action . constructor . mutation ) { return action . constructor . mutation ; } return action . mutation ; } export function isMutation ( action ) { return typeof getMutation ( action ) !== 'undefined' ; } export function getNameOfMutation ( mutation ) { const def = getMutationDefinition ( mutation ) ; const field = getFirstField ( def ) ; return field . name . value ; } export function withUpdates < T , V > ( config , manager ) { const orgUpdate = config . update ; return { ... config , update : ( proxy , mutationResult ) => { const name = getNameOfMutation ( config . mutation ) ; const result = mutationResult . data && ( mutationResult . data as any ) [ name ] ; const cache = manager . cache ; const context = buildContext ( { cache : proxy , getCacheKey : buildGetCacheKey ( cache ) , } , manager . getClient ( ) ) ; const updates = manager . updates . get ( name ) ; if ( updates ) { const info = { name , variables : config . variables , result , } ; updates . forEach ( def => def . resolve ( info , context ) ) ; } if ( orgUpdate ) { orgUpdate ( proxy , mutationResult ) ; } } , } ; } export function buildActionFromResult < T , V > ( config , result ) { return { type : 'mutation' , options : config , ok : true , ... result , } ; } export function buildActionFromError < T , V > ( config , error ) { return { type : 'mutation' , options : config , ok : false , error , } ; }