Directives on scalars in Apollo GraphQL Server

Viewed 261

I have a Date defined as a Scalar in my schema.

Is there a way to define the rules regarding the legal values in only one place?

I could probably define a directive on FIELD_DEFINITION and apply it on each field of this type. However, I would like to do it once. Is that possible?

Here is my code. The CitizenshipCode is actually a string, limited to the values "us", "uk", "de", etc. I would like to implement the validation in a centralised way, rather than adding a directive to each field of this type:

scalar CitizenshipCode    # is it possible to implement the validation here?


type Client {
  id: ID!
  name: String
  citizenship: CitizenshipCode   #  instead of here...
  # other atts
}

type User {
  id: ID!
  email: String
  citizenship: CitizenshipCode   #  ... and here
  # other atts
}
1 Answers

May be you can use enum type or use custom schema in your code:

const { ApolloServer, gql, SchemaDirectiveVisitor } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');

const validCountryCodes = [ "US", "UK", "DE"];

const citizenshipCodeScalar = new GraphQLScalarType({
    name: 'CitizenshipCode',
    description: 'Allowed citizen ship codes',
    serialize(value) {
        return validCountryCodes.includes(value) ? value : "INVALID COUNTRY";
    },
    parseValue(value) {
        return validCountryCodes.includes(value) ? value : null;
    },
    parseLiteral(ast) {
        return ast.kind === Kind.STRING ? ast.value : null;
    }
});

const typeDefs = gql `
  scalar CitizenshipCode

  type Client {
    id: ID
    name: String
    citizenship: CitizenshipCode
  }

  type User {
    id: Int
    email: String
    citizenship: CitizenshipCode
  }

  type Query {
      clients: [Client]
      users: [User]
  }
`;

const resolvers = {
    Query: {
        clients: () => clients,
        users: () => users
    },
    CitizenshipCode: citizenshipCodeScalar
};

const client = [{
        id: 'client1',
        name: 'The Awakening',
        citizenship: 'US'
    },
    {
        id: 'client2',
        title: 'City of Glass',
        citizenship: 'CA',
    },
];

const users = [{
        id: 1,
        email: 'test1@test.com',
        citizenship: 'UK',
    },
    {
        id: 2,
        email: 'test2@test.com',
        citizenship: 'DE',
    },
];

const server = new ApolloServer({
    typeDefs,
    resolvers
});
Related