5
5
GraphQLSchema ,
6
6
InputObjectTypeDefinitionNode ,
7
7
InputValueDefinitionNode ,
8
+ Kind ,
8
9
NameNode ,
9
10
ObjectTypeDefinitionNode ,
10
11
TypeNode ,
@@ -68,12 +69,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
68
69
const appendArguments = argumentBlocks ? '\n' + argumentBlocks : '' ;
69
70
70
71
// Building schema for fields.
71
- const shape = node . fields
72
- ?. map ( field => {
73
- const fieldSchema = generateFieldYupSchema ( this . config , visitor , field , 2 ) ;
74
- return isNonNullType ( field . type ) ? fieldSchema : `${ fieldSchema } .optional()` ;
75
- } )
76
- . join ( ',\n' ) ;
72
+ const shape = shapeFields ( node . fields , this . config , visitor )
77
73
78
74
switch ( this . config . validationSchemaExportType ) {
79
75
case 'const' :
@@ -203,12 +199,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
203
199
visitor : Visitor ,
204
200
name : string
205
201
) {
206
- const shape = fields
207
- ?. map ( field => {
208
- const fieldSchema = generateFieldYupSchema ( this . config , visitor , field , 2 ) ;
209
- return isNonNullType ( field . type ) ? fieldSchema : `${ fieldSchema } .optional()` ;
210
- } )
211
- . join ( ',\n' ) ;
202
+ const shape = shapeFields ( fields , this . config , visitor )
212
203
213
204
switch ( this . config . validationSchemaExportType ) {
214
205
case 'const' :
@@ -229,6 +220,30 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
229
220
}
230
221
}
231
222
223
+ const shapeFields = ( fields : readonly ( FieldDefinitionNode | InputValueDefinitionNode ) [ ] | undefined , config : ValidationSchemaPluginConfig , visitor : Visitor ) => {
224
+ return fields ?. map ( field => {
225
+ let fieldSchema = generateFieldYupSchema ( config , visitor , field , 2 ) ;
226
+
227
+ if ( field . kind === Kind . INPUT_VALUE_DEFINITION ) {
228
+ const { defaultValue } = field ;
229
+
230
+ if ( defaultValue ?. kind === Kind . INT || defaultValue ?. kind === Kind . FLOAT || defaultValue ?. kind === Kind . BOOLEAN ) {
231
+ fieldSchema = `${ fieldSchema } .default(${ defaultValue . value } )` ;
232
+ }
233
+ if ( ( defaultValue ?. kind === Kind . STRING ) || ( defaultValue ?. kind === Kind . ENUM ) ) {
234
+ fieldSchema = `${ fieldSchema } .default("${ defaultValue . value } ")` ;
235
+ }
236
+ }
237
+
238
+ if ( isNonNullType ( field . type ) ) {
239
+ return fieldSchema
240
+ }
241
+
242
+ return `${ fieldSchema } .optional()` ;
243
+ } )
244
+ . join ( ',\n' ) ;
245
+ }
246
+
232
247
const generateFieldYupSchema = (
233
248
config : ValidationSchemaPluginConfig ,
234
249
visitor : Visitor ,
0 commit comments