1- import type { Resolver , ObjectTypeComposer } from 'graphql-compose' ;
1+ import { Resolver , ObjectTypeComposer , mapEachKey } from 'graphql-compose' ;
22import type { Model , Document } from 'mongoose' ;
33import type { ExtendedResolveParams , GenResolverOpts } from './index' ;
44import { getOrCreateErrorInterface } from '../utils/getOrCreateErrorInterface' ;
55import { skipHelperArgs , recordHelperArgs , filterHelperArgs , sortHelperArgs } from './helpers' ;
66import findOne from './findOne' ;
7+ import { GraphQLError } from 'graphql' ;
78
89export default function updateOne < TSource = Document , TContext = any > (
910 model : Model < any > ,
@@ -82,6 +83,9 @@ export default function updateOne<TSource = Document, TContext = any>(
8283 )
8384 ) ;
8485 }
86+
87+ // this feels weird
88+ const requestsErrors : any = resolveParams ?. projection ?. errors ;
8589 // We should get all data for document, cause Mongoose model may have hooks/middlewares
8690 // which required some fields which not in graphql projection
8791 // So empty projection returns all fields.
@@ -93,30 +97,60 @@ export default function updateOne<TSource = Document, TContext = any>(
9397 doc = await resolveParams . beforeRecordMutate ( doc , resolveParams ) ;
9498 }
9599
96- if ( doc && recordData ) {
100+ if ( recordData ) {
97101 doc . set ( recordData ) ;
98102
99- const validationErrors = doc . validateSync ( ) ;
100- let errors : {
103+ const validationErrors : any = await new Promise ( function ( resolve ) {
104+ doc . validate ( null , null , resolve ) ;
105+ } ) ;
106+ const errors : {
101107 path : string ;
102108 message : string ;
103- } [ ] ;
109+ value : any ;
110+ } [ ] = [ ] ;
111+
104112 if ( validationErrors && validationErrors . errors ) {
105- errors = [ ] ;
113+ if ( ! requestsErrors ) {
114+ // if client does not request `errors` field we throw Exception on to level
115+ throw new GraphQLError (
116+ validationErrors . message ,
117+ undefined ,
118+ undefined ,
119+ undefined ,
120+ undefined ,
121+ undefined ,
122+ {
123+ validationErrors : mapEachKey ( validationErrors . errors , ( e : any ) => {
124+ return {
125+ path : e . path ,
126+ message : e . message ,
127+ value : e . value ,
128+ } ;
129+ } ) ,
130+ }
131+ ) ;
132+ }
106133 Object . keys ( validationErrors . errors ) . forEach ( ( key ) => {
134+ const { message, value } = validationErrors . errors [ key ] ;
107135 errors . push ( {
108136 path : key ,
109- message : validationErrors . errors [ key ] . properties . message ,
137+ message,
138+ value,
110139 } ) ;
111140 } ) ;
112141 return {
113142 record : null ,
114143 recordId : null ,
115144 errors,
116145 } ;
146+ } else {
147+ await doc . save ( ) ;
148+ return {
149+ record : doc ,
150+ recordId : tc . getRecordIdFn ( ) ( doc ) ,
151+ errors : null ,
152+ } ;
117153 }
118-
119- await doc . save ( ) ;
120154 }
121155
122156 if ( doc ) {
0 commit comments