Skip to content

li-kai/graphql-scalar-types

Repository files navigation

GraphQL Scalar Types Build Status Coverage Status

GraphQL scalar types for validation of GraphQL objects.

The flexibility of GraphQL means validation for your schemas is possible. GraphQL Scalar Types allows you to build types easily using a fluent interface, similar to libraries like Joi.

npm i graphql graphql-scalar-types

Example

import 'GraphQLScalarTypes' from 'graphql-scalar-types';

export const GraphQLName = GraphQLScalarTypes.string('Name').min(0).max(36).create();
export const GraphQLAge = GraphQLScalarTypes.number('Age').min(0).max(120).create();

Using Apollo-Server

Here is a minimal example using Apollo Server:

const { ApolloServer, gql } = require('apollo-server');
const { default: GraphQLScalarTypes } = require('graphql-scalar-types');

const schemaString = gql`
  # Make sure to define the scalars in the schema string
  scalar Name
  scalar Email

  type Person {
    name: Name
    email: Email
  }

  type Query {
    successfulPerson: Person
    unsuccessfulPerson: Person
  }
`;

const resolverFunctions = {
  // Now define the resolvers using GraphQLScalarTypes
  Name: GraphQLScalarTypes.string('Name').min(1).create(),
  Email: GraphQLScalarTypes.string('Email').regex(/[\w\d]+@[\w\d]+\.\w+/, { name: 'Email Regex' }).create(),

  Query: {
    successfulPerson: () => ({
      name: 'Foo Bar',
      email: 'test@email.com'
    }),
    unsuccessfulPerson: () => ({
      name: '',
      email: 'invalid-email'
    })
  }
};

const server = new ApolloServer({
  typeDefs: schemaString,
  resolvers: resolverFunctions
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

API

constructor

Constructs a builder with a name for the GraphQLScalar.

Parameters

Examples

const GraphQLStringBuilder = GraphQLScalarTypes.string('Name');
const GraphQLNumberBuilder = GraphQLScalarTypes.number('Age');
const GraphQLBooleanBuilder = GraphQLScalarTypes.boolean('SpecialFalsy');

describe

Gives a description to the GraphQLScalar.

Parameters

nonNull

Makes the GraphQLScalar reject null as a value.

Parameters

  • isNonNull boolean Default value is true. (optional, default true)

clone

Clones the builder.

create

Generates the GraphQLScalar.

Returns GraphQLScalarType<TInternal, TExternal>

BooleanScalar

Extends Base

Boolean scalar type that represents boolean data. By itself, it is essentially the GraphQLBoolean type.

truthy

Converts additional values to true during serialization. Accepts a value or an array of values.

Parameters

  • params ...any

falsy

Converts additional values to false during serialization. Accepts a value or an array of values.

Parameters

  • params ...any

DateScalar

Extends Base

String scalar type that takes in string data. By itself, it is essentially the GraphQLString type.

NumberScalar

Extends Base

Number scalar type that represents numerical data. By itself, it is essentially the GraphQLFloat type.

min

Specifies the minimum number allowed (inclusive).

Parameters

max

Specifies the maximum number allowed (inclusive).

Parameters

greater

Specifies that the value must be greater than the limit.

Parameters

lesser

Specifies that the value must be lesser than the limit.

Parameters

integer

Requires the number to be an integer from -(2^31) and 2^31 - 1. As per the GraphQL Spec, Integers are only treated as valid when a valid 32-bit signed integer, providing the broadest support across platforms.

precision

Specifies the maximum number of decimal places allowed.

Parameters

multiple

Specifies that the number must be a multiple of base.

Parameters

positive

Specifies that the number must be positive (>0).

negative

Specifies that the number must be negative (<0).

StringScalar

Extends Base

String scalar type that represents string data. By itself, it is essentially the GraphQLString type.

min

Specifies the minimum number of string characters allowed.

Parameters

max

Specifies the maximum number of string characters allowed.

Parameters

length

Specifies the exact number of string characters required.

Parameters

truncate

Specifies the length of the string to be truncated to if it exceeds.

Parameters

alphanum

Requires the string value to only contain a-z, A-Z, and 0-9.

creditCard

Requires the string value to be a credit card number.

regex

Requires the string value to match the regex test.

Parameters

  • pattern RegExp
  • options boolean name for regexp pattern and invert to disallow pattern instead. (optional, default {name:'',invert:false})

replace

Replaces the regex matches of the string with the replacement. Equivalent to String.prototype.replace.

Parameters

trim

Trims the string.

uppercase

lowercase

base64

Requires the string to be a valid base64 string.

hex

Requires the string to be a valid hexadecimal string.

validate

Given a value and a GraphQL type, determine if the value will be accepted for that type.

Parameters

  • value any
  • type GraphQLInputType

Returns Array<string>