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
@@ -75,7 +82,6 @@ export default function updateOne<TSource = Document, TContext = any>(
7582 )
7683 ) ;
7784 }
78-
7985 // We should get all data for document, cause Mongoose model may have hooks/middlewares
8086 // which required some fields which not in graphql projection
8187 // So empty projection returns all fields.
@@ -89,13 +95,32 @@ export default function updateOne<TSource = Document, TContext = any>(
8995
9096 if ( doc && recordData ) {
9197 doc . set ( recordData ) ;
98+
99+ const validationErrors = doc . validateSync ( ) ;
100+ let errors = null ;
101+ if ( validationErrors && validationErrors . errors ) {
102+ errors = [ ] ;
103+ Object . keys ( validationErrors . errors ) . forEach ( ( key ) => {
104+ errors . push ( {
105+ path : key ,
106+ messages : [ validationErrors . errors [ key ] . properties . message ] ,
107+ } ) ;
108+ } ) ;
109+ return {
110+ record : null ,
111+ recordId : null ,
112+ errors,
113+ } ;
114+ }
115+
92116 await doc . save ( ) ;
93117 }
94118
95119 if ( doc ) {
96120 return {
97121 record : doc ,
98122 recordId : tc . getRecordIdFn ( ) ( doc ) ,
123+ errors : null ,
99124 } ;
100125 }
101126
0 commit comments