-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGraphQLValidatedString.js
More file actions
123 lines (103 loc) · 2.38 KB
/
GraphQLValidatedString.js
File metadata and controls
123 lines (103 loc) · 2.38 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const {Kind} = require('graphql/language');
const GraphQLValidatedScalar = require('./GraphQLValidatedScalar');
class GraphQLValidatedString extends GraphQLValidatedScalar {
constructor (args = {}) {
if (!args.name) {
args.name = 'String';
}
super(args);
this.validator(String);
}
validKinds () {
return [Kind.STRING];
}
validTypes () {
return ['string'];
}
regex (pattern) {
if (!(pattern instanceof RegExp)) {
pattern = new RegExp(pattern);
}
return this.validator((str)=> {
if (pattern.test(str)) {
return str;
} else {
throw new TypeError(`${this.name} does not match ${pattern}: ${str}`);
}
});
}
existsIn (arr) {
return this.validator((str)=> {
const result = arr.find((el)=> {
return el === str;
});
if (result) {
return str;
} else {
throw new TypeError(`'${str}' was not present in array`);
}
});
}
length (length) {
return this.validator((str)=> {
let valid;
if (length.min || length.max) {
const {
min = -Infinity,
max = Infinity
} = length;
valid = (str.length >= min) && (str.length <= max);
} else {
valid = (str.length === length);
}
if (valid) {
return str;
} else {
throw new TypeError(`${this.name} has invalid length: ${str}`);
}
});
}
nonempty () {
return this.length({min: 1});
}
trim () {
return this.validator((str)=> {
return str.trim();
});
}
replace (pattern, replacement) {
return this.validator((str)=> {
return str.replace(pattern, replacement);
});
}
squish () {
this.trim();
return this.replace(/\s+/g, ' ');
}
truncate (length) {
return this.validator((str)=> {
return str.substring(0, length);
});
}
// https://stackoverflow.com/a/475217/178043
base64 () {
return this.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/);
}
hex () {
return this.regex(/^[a-f0-9]+$/i);
}
alphanumeric () {
return this.regex(/^[a-zA-Z0-9]+$/);
}
toUpperCase () {
return this.validator((str)=> {
return str.toUpperCase();
});
}
toLowerCase () {
return this.validator((str)=> {
return str.toLowerCase();
});
}
}
module.exports = GraphQLValidatedString;