Giter VIP home page Giter VIP logo

graphql-schema-from-json's Introduction

graphql-schema-from-json

Guess a GraphQL schema from json data.

Installation

npm install --save graphql-schema-from-json

or

yarn add graphql-schema-from-json

Usage

import getSchemaFromData from 'graphql-schema-from-json';
import { printSchema } from 'graphql';

const data = {
    posts: [
        { id: 1, title: "Lorem Ipsum", views: 254, user_id: 123 },
        { id: 2, title: "Sic Dolor amet", views: 65, user_id: 456 },
    ],
    users: [
        { id: 123, name: "John Doe" },
        { id: 456, name: "Jane Doe" }
    ],
    comments: [
        { id: 987, post_id: 1, body: "Consectetur adipiscing elit", date: new Date('2017-07-03') },
        { id: 995, post_id: 1, body: "Nam molestie pellentesque dui", date: new Date('2017-08-17') }
    ]
}

// Get the schema as a JSON object
const schema = getSchemaFromData(data);

// Print the GQL for this schema
console.log(printSchema(schema));

Generated Types and Queries

Based on your data, graphql-schema-from-json will generate a schema with one type per entity, as well as 3 query types and 3 mutation types. For instance for the Post entity:

type Query {
    Post(id: ID!): Post
    allPosts(page: Int, perPage: Int, sortField: String, sortOrder: String, filter: PostFilter): [Post]
    _allPostsMeta(page: Int, perPage: Int, sortField: String, sortOrder: String, filter: PostFilter): ListMetadata
}
type Mutation {
    createPost(data: String): Post
    updatePost(data: String): Post
    removePost(id: ID!): Boolean
}
type Post {
    id: ID!
    title: String!
    views: Int!
    user_id: ID!
    User: User
    Comments: [Comment]
}
type PostFilter {
    q: String
    id: ID
    title: String
    views: Int
    views_lt: Int
    views_lte: Int
    views_gt: Int
    views_gte: Int
    user_id: ID
}
type ListMetadata {
    count: Int!
}
scalar Date

By convention, graphql-schema-from-json expects all entities to have an id field that is unique for their type - it's the entity primary key. The type of every field is inferred from the values, so for instance, Post.title is a String!, and Post.views is an Int!. When all entities have a value for a field, graphql-schema-from-json makes the field type non nullable (that's why Post.views type is Int! and not Int).

For every field named *_id, graphql-schema-from-json creates a two-way relationship, to let you fetch related entities from both sides. For instance, the presence of the user_id field in the posts entity leads to the ability to fetch the related User for a Post - and the related Posts for a User.

The all* queries accept parameters to let you sort, paginate, and filter the list of results. You can filter by any field, not just the primary key. For instance, you can get the posts written by user 123. graphql-schema-from-json also adds a full-text query field named q, and created range filter fields for numeric and date fields. The detail of all available filters can be seen in the generated *Filter type.

GraphQL Usage

Here is how you can use the queries and mutations generated for your data, using Post as an example:

Query / Mutation Result
// get a single entity, by id
{
    Post(id: 1) {
        id
        title
        views
        user_id
    }
}
            
{
    "data": {
        "Post": {
            "id": 1,
            "title": "Lorem Ipsum",
            "views": 254,
            "user_id": 123
        }
    }
}
            
// include many-to-one relationships
{
    Post(id: 1) {
        title
        User {
            name
        }
    }
}
            
{
    "data": {
        "Post": {
            "title": "Lorem Ipsum",
            "User": {
                "name": "John Doe"
            }
        }
    }
}
            
// include one-to-many relationships
{
    Post(id: 1) {
        title
        Comments {
            body
        }
    }
}
            
{
    "data": {
        "Post": {
            "title": "Lorem Ipsum",
            "Comments": [
                { "body": "Consectetur adipiscing elit" },
                { "body": "Nam molestie pellentesque dui" },
            ]
        }
    }
}
            
// get a list of entities for a type
{
    allPosts {
        title
        views
    }
}
            
{
    "data": {
        "allPosts": [
            { "title": "Lorem Ipsum", views: 254 },
            { "title": "Sic Dolor amet", views: 65 }
        ]
    }
}
            
// paginate the results
{
    allPosts(page: 0, perPage: 1) {
        title
        views
    }
}
            
{
    "data": {
        "allPosts": [
            { "title": "Lorem Ipsum", views: 254 },
        ]
    }
}
            
// sort the results by field
{
    allPosts(sortField: "title", sortOrder: "desc") {
        title
        views
    }
}
            
{
    "data": {
        "allPosts": [
            { "title": "Sic Dolor amet", views: 65 }
            { "title": "Lorem Ipsum", views: 254 },
        ]
    }
}
            
// filter the results using the full-text filter
{
    allPosts({ filter: { q: "lorem" }}) {
        title
        views
    }
}
            
{
    "data": {
        "allPosts": [
            { "title": "Lorem Ipsum", views: 254 },
        ]
    }
}
            
// filter the result using any of the entity fields
{
    allPosts(views: 254) {
        title
        views
    }
}
            
{
    "data": {
        "allPosts": [
            { "title": "Lorem Ipsum", views: 254 },
        ]
    }
}
            
// number fields get range filters
// -lt, _lte, -gt, and _gte
{
    allPosts(views_gte: 200) {
        title
        views
    }
}
            
{
  "data": {
        "allPosts": [
            { "title": "Lorem Ipsum", views: 254 },
        ]
  }
}
            

Roadmap

  • Allow to override the primary key for each entity
  • Allow to override the relationship detection

Contributing

Use Prettier formatting and make sure you include unit tests. The project includes a Makefile to automate usual developer tasks:

make install
make build
make test
make watch
make format

License

graphql-schema-from-json is licensed under the MIT Licence, sponsored and supported by marmelab.

graphql-schema-from-json's People

Contributors

alexisjanvier avatar dependabot[bot] avatar djhi avatar euzebe avatar fzaninotto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-schema-from-json's Issues

entities.reduce is not a function

Hi, thanks for creating this repo: could save me a bunch of headaches in the future! But for now, I'm facing this error:

TypeError: entities.reduce is not a function

The object I'd like to parse for a schema looks as follows:

{
  "title": "Dough, Jane",
  "requester": "Dough, Jane",
  "address": "Building 1000",
  "approver": "",
  "assignment": "Guest",
  "attachedId": "",
  "audio": "1-2 audio sources",
  "location": "LOS ANGELES BUREAU"
}

My conversion code looks as follows:

const getSchemaFromData = require('graphql-schema-from-json').default;
const { printSchema } = require('graphql');

let schema = getSchemaFromData(myJSONObjectAbove);

And ideas?

Error with showing results

I used the code in the example & ran 'npm start'

"start": "babel-node index.js --presets es2015,stage-2"
Now using node v8.9.0 (npm v5.5.1)
me@me-Latitude-E7470:~/Development/Projects/g$ npm start
> [email protected] start /home/me/Development/Projects/g
> babel-node index.js --presets es2015,stage-2

/home/me/Development/Projects/g/node_modules/graphql/jsutils/invariant.js:18
    throw new Error(message);
    ^

Error
    at invariant (/home/me/Development/Projects/g/node_modules/graphql/jsutils/invariant.js:18:11)
    at printType (/home/me/Development/Projects/g/node_modules/graphql/utilities/schemaPrinter.js:151:83)
    at Array.map (<anonymous>)
    at printFilteredSchema (/home/me/Development/Projects/g/node_modules/graphql/utilities/schemaPrinter.js:80:87)
    at printSchema (/home/me/Development/Projects/g/node_modules/graphql/utilities/schemaPrinter.js:44:10)
    at Object.<anonymous> (/home/me/Development/Projects/g/index.js:26:13)
    at Module._compile (module.js:635:30)
    at loader (/home/me/Development/Projects/g/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/home/me/Development/Projects/g/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:554:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `babel-node index.js --presets es2015,stage-2`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/me/.npm/_logs/2017-11-03T12_10_43_198Z-debug.log

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.