forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslug.js
More file actions
31 lines (26 loc) · 779 Bytes
/
slug.js
File metadata and controls
31 lines (26 loc) · 779 Bytes
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
import { Kind, GraphQLError, GraphQLScalarType } from 'graphql'
const validate = (value) => {
const SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
if (typeof value !== 'string') {
throw new TypeError(`Value is not string: ${typeof value}`)
}
if (!SLUG_REGEX.test(value)) {
throw new TypeError(`Value is not a valid slug: ${value}`)
}
return value
}
export const Slug = new GraphQLScalarType({
name: 'Slug',
description:
'A field whose values contain numbers, letters, dashes, and underscores.',
serialize: validate,
parseValue: validate,
parseLiteral(ast) {
if (ast.kind !== Kind.STRING) {
throw new GraphQLError(
`Can only validate strings as slug but got a: ${ast.kind}`,
)
}
return validate(ast.value)
},
})