-
Notifications
You must be signed in to change notification settings - Fork 133
/
ObjectID.ts
54 lines (44 loc) · 1.47 KB
/
ObjectID.ts
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
import { GraphQLScalarType, Kind, ValueNode } from 'graphql';
import { createGraphQLError } from '../error.js';
const MONGODB_OBJECTID_REGEX = /*#__PURE__*/ /^[A-Fa-f0-9]{24}$/;
export const GraphQLObjectID = /*#__PURE__*/ new GraphQLScalarType({
name: 'ObjectID',
description:
'A field whose value conforms with the standard mongodb object ID as described here: https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectId. Example: 5e5677d71bdc2ae76344968c',
serialize(value: string) {
if (!MONGODB_OBJECTID_REGEX.test(value)) {
throw createGraphQLError(`Value is not a valid mongodb object id of form: ${value}`);
}
return value;
},
parseValue(value: string) {
if (!MONGODB_OBJECTID_REGEX.test(value)) {
throw createGraphQLError(`Value is not a valid mongodb object id of form: ${value}`);
}
return value;
},
parseLiteral(ast: ValueNode) {
if (ast.kind !== Kind.STRING) {
throw createGraphQLError(
`Can only validate strings as mongodb object id but got a: ${ast.kind}`,
{
nodes: [ast],
},
);
}
if (!MONGODB_OBJECTID_REGEX.test(ast.value)) {
throw createGraphQLError(`Value is not a valid mongodb object id of form: ${ast.value}`, {
nodes: ast,
});
}
return ast.value;
},
extensions: {
codegenScalarType: 'string',
jsonSchema: {
title: 'ObjectID',
type: 'string',
pattern: MONGODB_OBJECTID_REGEX.source,
},
},
});