-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
string.js
58 lines (47 loc) · 1.88 KB
/
string.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
const { GraphQLScalarType } = require('graphql')
const { GraphQLError } = require('graphql/error')
const { contains, isLength } = require('validator')
const formats = require('./formats')
module.exports = class ConstraintStringType extends GraphQLScalarType {
constructor (type, args) {
super({
name: `ConstraintString`,
serialize (value) {
return type.serialize(value)
},
parseValue (value) {
value = type.serialize(value)
if (args.minLength && !isLength(value, { min: args.minLength })) {
throw new GraphQLError(`Must be at least ${args.minLength} characters in length`)
}
if (args.maxLength && !isLength(value, { max: args.maxLength })) {
throw new GraphQLError(`Must be no more than ${args.maxLength} characters in length`)
}
if (args.startsWith && !value.startsWith(args.startsWith)) {
throw new GraphQLError(`Must start with ${args.startsWith}`)
}
if (args.endsWith && !value.endsWith(args.endsWith)) {
throw new GraphQLError(`Must end with ${args.endsWith}`)
}
if (args.contains && !contains(value, args.contains)) {
throw new GraphQLError(`Must contain ${args.contains}`)
}
if (args.notContains && contains(value, args.notContains)) {
throw new GraphQLError(`Must not contain ${args.notContains}`)
}
if (args.pattern && !new RegExp(args.pattern).test(value)) {
throw new GraphQLError(`Must match ${args.pattern}`)
}
if (args.format) {
const formatter = formats[args.format]
if (!formatter) throw new GraphQLError(`Invalid format type ${args.format}`)
formatter(value) // Will throw if invalid
}
return type.parseValue(value)
},
parseLiteral (ast) {
return type.parseLiteral(ast)
}
})
}
}