This repository has been archived by the owner on Mar 31, 2023. It is now read-only.
forked from L-L-Cool-J/graphql-constraint-directive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (70 loc) · 2.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const {
DirectiveLocation,
GraphQLDirective,
GraphQLInt,
GraphQLFloat,
GraphQLNonNull,
GraphQLString,
isWrappingType,
isNamedType
} = require('graphql')
const { SchemaDirectiveVisitor } = require('graphql-tools')
const ConstraintStringType = require('./scalars/string')
const ConstraintNumberType = require('./scalars/number')
class ConstraintDirective extends SchemaDirectiveVisitor {
static getDirectiveDeclaration (directiveName, schema) {
return new GraphQLDirective({
name: directiveName,
locations: [
DirectiveLocation.FIELD_DEFINITION,
DirectiveLocation.INPUT_FIELD_DEFINITION
],
args: {
/* Strings */
minLength: { type: GraphQLInt },
maxLength: { type: GraphQLInt },
startsWith: { type: GraphQLString },
endsWith: { type: GraphQLString },
contains: { type: GraphQLString },
notContains: { type: GraphQLString },
pattern: { type: GraphQLString },
format: { type: GraphQLString },
/* Numbers (Int/Float) */
min: { type: GraphQLFloat },
max: { type: GraphQLFloat },
exclusiveMin: { type: GraphQLFloat },
exclusiveMax: { type: GraphQLFloat },
multipleOf: { type: GraphQLFloat }
}
})
}
visitInputFieldDefinition (field) {
this.wrapType(field)
}
visitFieldDefinition (field) {
this.wrapType(field)
}
wrapType (field) {
const fieldName = field.astNode.name.value
if (field.type instanceof GraphQLNonNull && field.type.ofType === GraphQLString) {
field.type = new GraphQLNonNull(new ConstraintStringType(fieldName, field.type.ofType, this.args))
} else if (field.type === GraphQLString) {
field.type = new ConstraintStringType(fieldName, field.type, this.args)
} else if (field.type instanceof GraphQLNonNull && (field.type.ofType === GraphQLFloat || field.type.ofType === GraphQLInt)) {
field.type = new GraphQLNonNull(new ConstraintNumberType(fieldName, field.type.ofType, this.args))
} else if (field.type === GraphQLFloat || field.type === GraphQLInt) {
field.type = new ConstraintNumberType(fieldName, field.type, this.args)
} else {
throw new Error(`Not a scalar type: ${field.type}`)
}
const typeMap = this.schema.getTypeMap();
let type = field.type;
if (isWrappingType(type)) {
type = type.ofType;
}
if (isNamedType(type) && !typeMap[type.name]) {
typeMap[type.name] = type;
}
}
}
module.exports = ConstraintDirective