All Projects → HerbCaudill → Jsonschema2graphql

HerbCaudill / Jsonschema2graphql

Licence: mit
Convert JSON schema to GraphQL types

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Jsonschema2graphql

Rxdb
🔄 A client side, offline-first, reactive database for JavaScript Applications
Stars: ✭ 16,670 (+69358.33%)
Mutual labels:  graphql, json-schema
Graphql To Json Schema
GraphQL Schema to JSON Schema
Stars: ✭ 87 (+262.5%)
Mutual labels:  graphql, json-schema
Rest Layer
REST Layer, Go (golang) REST API framework
Stars: ✭ 1,068 (+4350%)
Mutual labels:  graphql, json-schema
Quicktype
Generate types and converters from JSON, Schema, and GraphQL
Stars: ✭ 7,459 (+30979.17%)
Mutual labels:  graphql, json-schema
Gatsby Simplefolio
⚡️ A minimal Gatsby portfolio template for Developers
Stars: ✭ 895 (+3629.17%)
Mutual labels:  graphql
Ionic Apollo Simple App
Explains how to develop Ionic application with Apollo GraphQL client
Stars: ✭ 16 (-33.33%)
Mutual labels:  graphql
Graphql Redis Subscriptions
A graphql subscriptions implementation using redis and apollo's graphql-subscriptions
Stars: ✭ 829 (+3354.17%)
Mutual labels:  graphql
Gatsby Starter Personal Blog
A ready to use, easy to customize, fully equipped GatsbyJS blog starter with 'like app' layout and views transitions.
Stars: ✭ 817 (+3304.17%)
Mutual labels:  graphql
Apollo Link Maxage
An Apollo Link to invalidate cached queries
Stars: ✭ 23 (-4.17%)
Mutual labels:  graphql
Graphql Mst
Convert GraphQL to mobx-state-tree models
Stars: ✭ 22 (-8.33%)
Mutual labels:  graphql
React Hasura Todo
A react todo app using Hasura Graphql engine
Stars: ✭ 18 (-25%)
Mutual labels:  graphql
Graph Node
Graph Node indexes data from blockchains such as Ethereum and serves it over GraphQL
Stars: ✭ 884 (+3583.33%)
Mutual labels:  graphql
Graphql Server Demo
GraphQL server demo with nodejs
Stars: ✭ 19 (-20.83%)
Mutual labels:  graphql
Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (+3362.5%)
Mutual labels:  json-schema
Graphql Moltin Server
⚛️ GraphQL + Moltin + GraphQL Yoga 🧘
Stars: ✭ 22 (-8.33%)
Mutual labels:  graphql
Api Platform
Create REST and GraphQL APIs, scaffold Jamstack webapps, stream changes in real-time.
Stars: ✭ 7,144 (+29666.67%)
Mutual labels:  graphql
Strawberry
A new GraphQL library for Python 🍓
Stars: ✭ 891 (+3612.5%)
Mutual labels:  graphql
Swapi Graphql Lambda
A GraphQL schema hosted in AWS Lambda wrapping http://swapi.co/
Stars: ✭ 19 (-20.83%)
Mutual labels:  graphql
Electron Crash Report Service
Aggregate crash reports for Electron apps
Stars: ✭ 17 (-29.17%)
Mutual labels:  json-schema
Diversidad Media
Diversidad Media is a platform to generate more diverse spaces, through Movies, Books, Music, and others. The project is in fast growth and there are many things to do. We are still covering the basics.
Stars: ✭ 17 (-29.17%)
Mutual labels:  graphql

logo

JSON Schema to GraphQL converter

This library exports a single function, convert, which converts one or more JSON schemas to a GraphQL schema.

Installation

Install with yarn:

yarn add jsonschema2graphql

Usage

You can convert a schema expressed as an object literal:

import { printSchema } from 'graphql'
import convert from 'jsonschema2graphql'

const jsonSchema = {
  $id: '#/person',
  type: 'object',
  properties: {
    name: {
      type: 'string',
    },
    age: {
      type: 'integer',
    },
  },
}

const schema = convert({ jsonSchema })

console.log(printSchema(schema))

Output

type Person {
  name: String
  age: Int
}
type Query {
  people: [Person]
}

Alternatively, you can provide the schema as JSON text.

const schema = convert({
  jsonSchema: `{
    "$id": "person",
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      },
      "age": {
        "type": "integer"
      }
    }
  }`,
})

This will generate the same result as above.

To generate more than one type, provide an array of JSON schemas in either object or text form.

const orange = {
  $id: '#/Orange',
  type: 'object',
  properties: {
    color: {
      type: 'string',
    },
  },
}

const apple = {
  $id: '#/Apple',
  type: 'object',
  properties: {
    color: { type: 'string' },
    bestFriend: {
      $ref: '#/Orange', // <-- reference foreign type using $ref
    },
  },
}

const schema = convert({ jsonSchema: [orange, apple] })

Output

type Apple {
  color: String
  bestFriend: Orange
}
type Orange {
  color: String
}
type Query {
  oranges: [Orange]
  apples: [Apple]
}`

Custom root types (Query, Mutation, Subscription)

By default, a Query type is added to the schema, with one field defined per type, returning an array of that type. So for example, if you have an Person type and a Post type, you'll get a Query type that looks like this:

type Query {
  people: [Person]
  posts: [Posts]
}

(Note that the generated name for the field is automatically pluralized.)

By default, no Mutation or Subscription types are created.

To create a custom Query type and to add Mutation and/or Subscription blocks, provide an entryPoints callback that takes a hash of GraphQL types and returns Query, Mutation (optional), and Subscription (optional) blocks. Each block consists of a hash of GraphQLFieldConfig objects.

const jsonSchema = [log, user, family]

const entryPoints = types => {
  return {
    query: new GraphQLObjectType({
      name: 'Query',
      fields: {
        family: { type: types['Family'] },
        user: {
          type: types['User'],
          args: {
            email: { type: types['Email'] },
          },
        },
      },
    }),
    mutation: new GraphQLObjectType({
      name: 'Mutation',
      fields: {
        stop: { type: types['Log'] },
      },
    }),
  }
}

const schema = convert({ jsonSchema, entryPoints })

See the GraphQL guide "Constructing Types" for more on how to create GraphQL types programmatically.

Note that any types that are not referenced directly or indirectly by your root types will be omitted from the final schema.

JSON schema feature support

Note: This package is designed for use with schemas compliant with JSON Schema Draft 7.

For clarity, the following examples only show the converted types; the Query type is omitted from the output.

Basic types

Input

{
  $id: '#/Person',
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'integer' },
    score: { type: 'number' },
    isMyFriend: { type: 'boolean' },
  },
}

Output

type Person {
  name: String
  age: Int
  score: Float
  isMyFriend: Boolean
}

Array types

Input

const jsonSchema = {
  $id: '#/Person',
  type: 'object',
  properties: {
    name: {
      type: 'string',
    },
    luckyNumbers: {
      type: 'array',
      items: {
        type: 'integer',
      },
    },
    favoriteColors: {
      type: 'array',
      items: {
        type: 'string',
      },
    },
  },
}

Output

type Person {
  name: String
  luckyNumbers: [Int!]
  favoriteColors: [String!]
}

Enums

Input

const jsonSchema = {
  $id: '#/Person',
  type: 'object',
  properties: {
    height: {
      type: 'string',
      enum: ['tall', 'average', 'short'], // <-- enum
    },
  },
}

Output

type Person {
  height: PersonHeight
}

enum PersonHeight {
  tall
  average
  short
}

Required fields

Input

const jsonSchema = {
  $id: '#/Widget',
  type: 'object',
  properties: {
    somethingRequired: { type: 'integer' },
    somethingOptional: { type: 'integer' },
    somethingElseRequired: { type: 'integer' },
  },
  required: ['somethingRequired', 'somethingElseRequired'],
}

Output

type Widget {
  somethingRequired: Int!
  somethingOptional: Int
  somethingElseRequired: Int!
}

Foreign references using $ref

Input

const jsonSchema = {
  {
    $id: '#/Orange',
    type: 'object',
    properties: {
      color: {
        type: 'string',
      },
    },
  },
  {
    $id: '#/Apple',
    type: 'object',
    properties: {
      color: { type: 'string' },
      bestFriend: {
        $ref: '#/Orange', // <-- reference foreign type using $ref
      },
    },
  },
]

Output

type Apple {
  color: String
  bestFriend: Orange
}

type Orange {
  color: String
}

Union types using oneOf

Input

const jsonSchema = {
  {
    $id: '#/Parent',
    type: 'object',
    properties: {
      type: { type: 'string' },
      name: { type: 'string' },
    },
  },
  {
    $id: '#/Child',
    type: 'object',
    properties: {
      type: { type: 'string' },
      name: { type: 'string' },
      parent: { $ref: '#/Parent' },
      bestFriend: { $ref: '#/Person' },
      friends: {
        type: 'array',
        items: { $ref: '#/Person' },
      },
    },
  },
  {
    $id: '#/Person',
    oneOf: [{ $ref: '#/Parent' }, { $ref: '#/Child' }],
  },
]

Output

type Child {
  type: String
  name: String
  parent: Parent
  bestFriend: Person
  friends: [Person!]
}

type Parent {
  type: String
  name: String
}

union Person = Parent | Child

Properties defined as oneOf with if/then are also supported. For example, this:

const jsonSchema = {
  $id: '#/Person',
  oneOf: [
    {
      if: { properties: { type: { const: 'Parent' } } },
      then: { $ref: '#/Parent' },
    },
    {
      if: { properties: { type: { const: 'Child' } } },
      then: { $ref: '#/Child' },
    },
  ],
}

generates the same union type as above:

union Person = Parent | Child

Descriptions for types and fields

Input

const jsonSchema = {
  $id: '#/person',
  type: 'object',
  description: 'An individual human being.',
  properties: {
    name: {
      type: 'string',
      description: 'The full name of the person.',
    },
    age: {
      type: 'integer',
      description: "The elapsed time (in years) since the person's birth.",
    },
  },
}

Output

"""
An individual human being.
"""
type Person {
  """
  The full name of the person.
  """
  name: String
  """
  The elapsed time (in years) since the person's birth.
  """
  age: Int
}

To do

The following features are not currently supported, but I'd like to add them for completeness. Pull requests are welcome.

  • [ ] Combining JSON schemas with allOf, anyOf, or not
  • [ ] Generating GraphQL input types

Acknowledgements

Derived from json-schema-to-graphql-types by Matt Lavin ([email protected]).

Built with typescript-starter by Jason Dreyzehner ([email protected]).

MIT License

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].