11import type { Resolver , ObjectTypeComposer } from 'graphql-compose' ;
22import type { Model , Document } from 'mongoose' ;
33import type { ExtendedResolveParams , GenResolverOpts } from './index' ;
4+ import { getOrCreateErrorPayload } from '../utils/getOrCreateErrorPayload' ;
45import { skipHelperArgs , recordHelperArgs , filterHelperArgs , sortHelperArgs } from './helpers' ;
56import findOne from './findOne' ;
67
@@ -20,6 +21,8 @@ export default function updateOne<TSource = Document, TContext = any>(
2021
2122 const findOneResolver = findOne ( model , tc , opts ) ;
2223
24+ getOrCreateErrorPayload ( tc ) ;
25+
2326 const outputTypeName = `UpdateOne${ tc . getTypeName ( ) } Payload` ;
2427 const outputType = tc . schemaComposer . getOrCreateOTC ( outputTypeName , ( t ) => {
2528 t . addFields ( {
@@ -31,6 +34,10 @@ export default function updateOne<TSource = Document, TContext = any>(
3134 type : tc ,
3235 description : 'Updated document' ,
3336 } ,
37+ errors : {
38+ type : '[ErrorPayload]' ,
39+ description : 'Errors that may occur, typically validations' ,
40+ } ,
3441 } ) ;
3542 } ) ;
3643
@@ -73,7 +80,6 @@ export default function updateOne<TSource = Document, TContext = any>(
7380 )
7481 ) ;
7582 }
76-
7783 // We should get all data for document, cause Mongoose model may have hooks/middlewares
7884 // which required some fields which not in graphql projection
7985 // So empty projection returns all fields.
@@ -87,13 +93,32 @@ export default function updateOne<TSource = Document, TContext = any>(
8793
8894 if ( doc && recordData ) {
8995 doc . set ( recordData ) ;
96+
97+ const validationErrors = doc . validateSync ( ) ;
98+ let errors = null ;
99+ if ( validationErrors && validationErrors . errors ) {
100+ errors = [ ] ;
101+ Object . keys ( validationErrors . errors ) . forEach ( ( key ) => {
102+ errors . push ( {
103+ path : key ,
104+ messages : [ validationErrors . errors [ key ] . properties . message ] ,
105+ } ) ;
106+ } ) ;
107+ return {
108+ record : null ,
109+ recordId : null ,
110+ errors,
111+ } ;
112+ }
113+
90114 await doc . save ( ) ;
91115 }
92116
93117 if ( doc ) {
94118 return {
95119 record : doc ,
96120 recordId : tc . getRecordIdFn ( ) ( doc ) ,
121+ errors : null ,
97122 } ;
98123 }
99124
0 commit comments