README
apollo-koa-constraint-directive
Allows using @constraint as a directive to validate input and output data. This module is for Apollo Graphql Koa middleware, and support the latest Apollo GraphQL version 2.
It is mainly based on the module from graphql-constraint-directive, which is for Apollo version 1 only. This module is an Inspired by Constraints Directives RFC and OpenAPI
Install
npm install apollo-koa-constraint-directive
Usage
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const { ApolloServer, makeExecutableSchema, gql } = require('apollo-server-koa')
const ConstraintDirective = require('apollo-koa-constraint-directive')
const app = new Koa()
const schemaDirectives = {
constraint: ConstraintDirective,
};
const typeDefs = gql`
scalar ValidateString
scalar ValidateNumber
directive @constraint(
# String constraints
minLength: Int
maxLength: Int
startsWith: String
endsWith: String
notContains: String
pattern: String
format: String
# Number constraints
min: Int
max: Int
exclusiveMin: Int
exclusiveMax: Int
multipleOf: Int
) on INPUT_FIELD_DEFINITION
type Query {
books: [Book]
}
type Book {
title: String
}
type Mutation {
createBook(input: BookInput): Book
}
input BookInput {
title: String! @constraint(minLength: 5, format: "email")
}`
const apollo = new ApolloServer({
schema: makeExecutableSchema({ typeDefs, schemaDirectives })
});
app.use(bodyParser())
apollo.applyMiddleware({ app })
app.listen(8000)
API
String
minLength
@constraint(minLength: 5)
Restrict to a minimum length
maxLength
@constraint(maxLength: 5)
Restrict to a maximum length
startsWith
@constraint(startsWith: "foo")
Ensure value starts with foo
endsWith
@constraint(endsWith: "foo")
Ensure value ends with foo
contains
@constraint(contains: "foo")
Ensure value contains foo
notContains
@constraint(notContains: "foo")
Ensure value does not contain foo
pattern
@constraint(pattern: "^[0-9a-zA-Z]*