Giter Site home page Giter Site logo

gql-to-yup's Introduction

GQL 2 Yup

GraphQL to Yup

Coverage Status Build & Test

๐Ÿค” Why?

Have you ever had a schema (gql) that you wanted to validate? Maybe it was for tests, or data ingestion, etc. This small library takes in a GQL Schema, extracts all the objects, unions, enums, etc, and exposes them as Yup valiation objects.. It also supports Dates and nested schemas.

๐Ÿ“ฆ Install

Both browser and Node.js compadible. Install with:

yarn add gql-to-yup

OR

npm i --save-dev gql-to-yup

๐Ÿƒ๐Ÿปโ€โ™€๏ธ How?

Take a path to a GQL file, a GQL string, or GraphQLSchema object, and pass it in:

import { GQL2Yup } from 'gql-to-yup';

// ...

const fromString = new GQL2Yup(`
  type Person {
    name: String!
    age: Int!
    address: String   # Not required
  }
`);

const Person = fromString.getEntity('Person') // returns Yup.object()
await Person.validate({
  name: 'Bruce Lee',
  age: 'twenty-seven' // Fails as this is not a number!
});
// Throws ValidationError: 'age must be a `number` type, but the final value was: `NaN` (cast from the value `"twenty-seven"`).'

And that's it!

โšก๏ธ API:

Basic usage

const pathToFile = './schema.gql';
const schema = new GQL2Yup(pathToFile);

const user = {
  firstName: 'Bruce',
  lastName: 'Lee',
  age: new Date(),
  deceased: true
}
await schema.getEntity('User').validate(user); // Returns user if valid

Enum

const gender = new GQL2Yup(`enum Gender {
  male, female
}`).getEntity('Gender');

await gender.validate('female') // Valid
await gender.validate('foobar') // Throws error

Numbers

Float and Int are both cast as yup.number()

const Foo = new GQL2Yup(`type Foo {
  float: Float!
  int: Int!
}`).getEntity('Foo');

await foo.validate({float: 1.1, int: 1) // Valid

Dates

This library uses MomentJS for date validation. It supports the following formats:

  • moment.ISO_8601
  • moment.RFC_2822
  • moment.defaultFormat
  • moment.defaultFormatUt
const Article = new GQL2Yup(`type Article {
  published: Date! # Many frameworks add this type
}`).getEntity('Article');

await Article.validate({published: new Date()) // Valid
await Article.validate({published: '08/01/2020') // Valid as string
await Article.validate({published: 'Not a date') // Throws error

Arrays

const Favourite = new GQL2Yup(`type Favourite {
  fruits: [String!]!
}`).getEntity('Favourite');

await Favourite.validate({fruits: ['apple', 'mango']) // Valid
await Favourite.validate({fruits: ['apple', false]) // Throws error

This will also work with custom objects

const Company = new GQL2Yup(`
  type Person {
    name: String!
    age: Int!
  }
  type Company {
    name: String!
    employees: [Person!]!
  }
`).getEntity('Company');

await Company.validate({
  name: 'Apple',
  employees: [
    {name: 'Tim Cook', age: 60},
    {name: 'Steve Jobs', age: 56},
  ]
}); // Valid

Unions

In GQL you can combine types. This is also available in this library

const Offer = new GQL2Yup(`
  enum Color { red, blue, green }
  type Product {
    name: String!
    price: Int!
    color: Color
  }
  type Service {
    name: String!
    price: Int!
    duration: Int!
  }
  type Offer = Product | Service
`).getEntity('Offer');

await Offer.validate({
  name: 'iPhone',
  price: 999,
  color: 'red'
}); // Valid (as a "Product")

await Offer.validate({
  name: 'Apple Care',
  price: 200,
  duration: 365
}); // Valid (as a "Service")

Exclude fields

Sometimes, it is useful to exlude certain properties from the generated validation schema. This might be used if, for example, your data requires a list of objects, but is sent instead, as a list of IDs. There are many cases for this.

The exlcude is passed as the second argument to new GQL2Yup() as an array of strings. It uses dot notation. This means you can ignore an entire entity, or an entity's propertery.

const Exclude = new GQL2Yup(
  `
    type Product {
      name: String!
      price: Int!
    }
    type Bundle {
      name: String!
      products: [Product!]!
    }
  `,
  ['Bundle.products'] // Here we ignore the 'products' property on the 'Bundle' entity
).getEntity('Bundle');

await Exclude.validate({
  name: 'Apple',
  products: ['id1', 'id2', 'id3'] // Usually this would fail
}); // Valid

Excluded properties can also be excluded across all types.

new GQL2Yup(
  './schema.gql'
  ['price'] // Ignore ALL price properties on ALL entities
):

gql-to-yup's People

Contributors

dependabot[bot] avatar tristanmatthias avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.