Skip to content

Commit

Permalink
feat: add getSchemaDSL method
Browse files Browse the repository at this point in the history
  • Loading branch information
vsimko committed Nov 13, 2018
1 parent b1ca607 commit c66917c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 30 deletions.
21 changes: 0 additions & 21 deletions constraint-directive.graphql

This file was deleted.

25 changes: 20 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const {
GraphQLDirective,
GraphQLInt,
GraphQLFloat,
GraphQLString
GraphQLString,
GraphQLSchema,
printSchema
} = require('graphql')

const {
Expand Down Expand Up @@ -70,15 +72,28 @@ const mapVerifiersFromArgs = mapObjIndexed((v, k) => allVerifiers[k](v))
* */
const verifyValue = fnlist => (...args) => map(fn => fn(...args), fnlist)

const prepareVerifyFn = compose(verifyValue, mapVerifiersFromArgs) // should be self-explanatory
const prepareVerifyFn = compose(
verifyValue,
mapVerifiersFromArgs
) // should be self-explanatory

module.exports = class extends SchemaDirectiveVisitor {
/**
* When using e.g. graphql-yoga, we need to include schema of this directive
* into our DSL, otherwise the graphql schema validator would report errors.
*/
static getSchemaDSL () {
const constraintDirective = this.getDirectiveDeclaration('constraint')
const schema = new GraphQLSchema({
directives: [constraintDirective]
})
return printSchema(schema)
}

static getDirectiveDeclaration (directiveName, schema) {
return new GraphQLDirective({
name: directiveName,
locations: [
DirectiveLocation.ARGUMENT_DEFINITION
],
locations: [DirectiveLocation.ARGUMENT_DEFINITION],
args: {
/* Strings */
minLength: { type: GraphQLInt },
Expand Down
11 changes: 7 additions & 4 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
const { readFileSync } = require('fs')
const { makeExecutableSchema } = require('graphql-tools')
const { GraphQLSchema } = require('graphql')

const constraint = require('../src/index')
const constraintSchemaDsl = readFileSync('constraint-directive.graphql', 'utf8')

describe('@constraint directive', () => {
it('should provide its own schema in DSL', () => {
const dsl = constraint.getSchemaDSL()
expect(dsl).toMatch('directive @constraint')
})

it('should work when used properly in other graphql schema', () => {
const withOtherSchema = `
${constraintSchemaDsl}
${constraint.getSchemaDSL()}
type Mutation {
signup(
name: String @constraint(maxLength:20)
Expand All @@ -24,7 +27,7 @@ describe('@constraint directive', () => {

it('should NOT work when using unknown parameter', () => {
const withOtherSchema = `
${constraintSchemaDsl}
${constraint.getSchemaDSL()}
type Mutation {
signup(
name: String @constraint(DUMMY:123)
Expand Down

0 comments on commit c66917c

Please sign in to comment.