Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import { UserInputError } from 'apollo-server-express';
2import { GraphQLScalarType, Kind } from 'graphql';
3
4import {
5 tryParseNonEmptyString,
6 type NonEmptyString,
7} from '../../utils/typescript-types.js';
8
9/**
10 * This scalar is needed for values that must be non-empty strings. This
11 * implementation borrows from the graphql-scalars library's implementation, but
12 * is adapted to use our NonEmptyString TS type.
13 */
14export default new GraphQLScalarType<NonEmptyString, NonEmptyString>({
15 name: 'NonEmptyString',
16 description: 'A string that must be non-empty.',
17 serialize(value) {
18 if (typeof value !== 'string') {
19 throw new UserInputError('Expected a string.');
20 }
21 return tryParseNonEmptyString(value);
22 },
23 parseValue: tryParseNonEmptyString,
24 parseLiteral(ast) {
25 if (ast.kind !== Kind.STRING) {
26 throw new UserInputError('NonEmptyString must be a string.');
27 }
28 return tryParseNonEmptyString(ast.value);
29 },
30
31 extensions: {
32 // This is allowed to be used by graphlql-codegen in the event that we omit
33 // this type from the scalar mapping in our codegen.yml file.
34 // TODO(maxdumas): Verify this by removing this type from the codegen.yml
35 codegenScalarType: 'string',
36 // This field isn't used by anything in our codebase right now, but including a
37 // jsonSchema for a custom scalar is standard practice in the
38 // `graphql-scalars` codebase, so we include it here as well for
39 // consistency. It's possible that this could aid with automatic client
40 // generation or documentation in the future.
41 jsonSchema: {
42 title: 'NonEmptyString',
43 type: 'string',
44 minLength: 1,
45 },
46 },
47});