• Stars
    star
    1,911
  • Rank 23,429 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Get a full fake GraphQL API with zero coding in less than 30 seconds.

json-graphql-server

travis (.org) github top language David. dependencies npm github contributors license prs welcome

Get a full fake GraphQL API with zero coding in less than 30 seconds.

Motivation

I'd love to learn GraphQL, but it seems that I first have to read a book about GraphQL Types and Queries, then install a gazillion npm packages.

  • About every developer

Start playing with GraphQL right away with json-graphql-server, a testing and mocking tool for GraphQL. All it takes is a JSON of your data.

Inspired by the excellent json-server.

Example

Follow the guide below starting from scratch, or see the example live on StackBlitz:

Open in StackBlitz

Create a db.js file.

Your data file should export an object where the keys are the entity types. The values should be lists of entities, i.e. arrays of value objects with at least an id key. For instance:

module.exports = {
    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') }
    ]
}

Start the GraphQL server on localhost, port 3000.

json-graphql-server db.js

To use a port other than 3000, you can run json-graphql-server db.js -p <your port here> or --port <your port here> To use a host other than localhost, you can run json-graphql-server db.js -h <your host here> or --host <your host here>

Now you can query your data in graphql. For instance, to issue the following query:

{
    Post(id: 1) {
        id
        title
        views
        User {
            name
        }
        Comments {
            date
            body
        }
    }
}

Go to http://localhost:3000/?query=%7B%20Post%28id%3A%201%29%20%7B%20id%20title%20views%20User%20%7B%20name%20%7D%20Comments%20%7B%20date%20body%20%7D%20%7D%20%7D. You'll get the following result:

{
    "data": {
        "Post": {
            "id": "1",
            "title": "Lorem Ipsum",
            "views": 254,
            "User": {
                "name": "John Doe"
            },
            "Comments": [
                { "date": "2017-07-03T00:00:00.000Z", "body": "Consectetur adipiscing elit" },
                { "date": "2017-08-17T00:00:00.000Z", "body": "Nam molestie pellentesque dui" },
            ]
        }
    }
}

The json-graphql-server accepts queries in GET and POST. Under the hood, it uses the express-graphql module. Please refer to their documentations for details about passing variables, etc.

Note that the server is GraphiQL enabled, so you can query your server using a full-featured graphical user interface, providing autosuggest, history, etc. Just browse http://localhost:3000/ to access it.

GraphiQL client using json-graphql-server

Install

npm install -g json-graphql-server

Generated Types and Queries

Based on your data, json-graphql-server 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
  createManyPost(data: [{data:String}]): [Post]
  updatePost(data: String): Post
  removePost(id: ID!): Post
}
type Post {
    id: ID!
    title: String!
    views: Int!
    user_id: ID!
    User: User
    Comments: [Comment]
}
type PostFilter {
    q: String
    id: ID
    id_neq: ID
    title: String
    title_neq: String
    views: Int
    views_lt: Int
    views_lte: Int
    views_gt: Int
    views_gte: Int
    views_neq: Int
    user_id: ID    
    user_id_neq: ID
}
type ListMetadata {
    count: Int!
}
scalar Date

By convention, json-graphql-server 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, json-graphql-server makes the field type non nullable (that's why Post.views type is Int! and not Int).

For every field named *_id, json-graphql-server 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. Json-graphql-server also adds a full-text query field named q, and created range filter fields for numeric and date fields. All types (excluding booleans and arrays) get a not equal filter. The detail of all available filters can be seen in the generated *Filter type.

Supported types

Type GraphQL Type Rule Example value
Id GraphQLID name === 'id' || name.substr(name.length - 3) === '_id' 1
Integer GraphQLInt Number.isInteger(value) 12
Numeric GraphQLFloat !isNaN(parseFloat(value)) && isFinite(value) 12.34
Boolean GraphQLBoolean typeof value === 'boolean' false
String GraphQLString typeof value === 'string' 'foo'
Array GraphQLList Array.isArray(value) ['bar'], [12, 34]
Date DateType (custom) value instanceof Date || isISODateString(value) new Date('2016-06-10T15:49:14.236Z'), '2016-06-10T15:49:14.236Z'
Object GraphQLJSON Object.prototype.toString.call(value) === '[object Object]' transport: { service: 'fakemail', auth: { user: '[email protected]', pass: 'f00b@r' } }

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(filter: { views: 254 }) {
    title
    views
  }
}
            
{
  "data": {
    "allPosts": [
      { "title": "Lorem Ipsum", views: 254 },
    ]
  }
}
            
// all fields (except boolean and array) get not equal filters
// -lt, _lte, -gt, and _gte
{
  allPosts(filter: { title_neq: "Lorem Ipsum" }) {
    title
    views
  }
}
            
{
  "data": {
    "allPosts": [
      { "title": "Some Other Title", views: 254 },
    ]
  }
}
            
// number fields get range filters
// -lt, _lte, -gt, and _gte
{
  allPosts(filter: { views_gte: 200 }) {
    title
    views
  }
}
            
{
  "data": {
    "allPosts": [
      { "title": "Lorem Ipsum", views: 254 },
    ]
  }
}
            

Usage with Node

Install the module locally:

npm install --save-dev json-graphql-server

Then use the jsonGraphqlExpress express middleware:

import express from 'express';
import jsonGraphqlExpress from 'json-graphql-server';

const PORT = 3000;
const app = express();
const data = {
    // ... your data
};
app.use('/graphql', jsonGraphqlExpress(data));
app.listen(PORT);

Usage in browser with XMLHttpRequest

Useful when using XMLHttpRequest directly or libraries such as axios.

Install with a script tag

Add a script tag referencing the library:

<script src="../lib/json-graphql-server.client.min.js"></script>

It will expose the JsonGraphqlServer as a global object:

<script type="text/javascript">
    window.addEventListener('load', function() {
        const data = [...];

        const server = JsonGraphqlServer({
            data,
            url: 'http://localhost:3000/graphql'
        });

        server.start();

        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:3000/graphql', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.onerror = function(error) {
            console.error(error);
        }
        xhr.onload = function() {
            const result = JSON.parse(xhr.responseText);
            console.log('data returned:', result);
            alert('Found ' + result.data.allPosts.length + ' posts');
        }
        const body = JSON.stringify({ query: 'query allPosts { allPosts { id } }' });
        xhr.send(body);
    });
</script>

Use with a bundler (webpack)

npm install json-graphql-server
import JsonGraphqlServer from 'json-graphql-server';

const data = [...];

const server = JsonGraphqlServer({
    data,
    url: 'http://localhost:3000/graphql'
});

server.start();

const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/graphql', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onerror = function(error) {
    console.error(error);
}
xhr.onload = function() {
    const result = JSON.parse(xhr.responseText);
    console.log('data returned:', result);
    alert('Found ' + result.data.allPosts.length + ' posts');
}
const body = JSON.stringify({ query: 'query allPosts { allPosts { id } }' });
xhr.send(body);

Usage in browser with fetch

import fetchMock from 'fetch-mock';
import JsonGraphqlServer from 'json-graphql-server';

const data = [...];
const server = JsonGraphqlServer({ data });

fetchMock.post('http://localhost:3000/graphql', server.getHandler());

fetch({
    url: 'http://localhost:3000/graphql',
    method: 'POST',
    body: JSON.stringify({ query: 'query allPosts { allPosts { id } }' })
})
.then(response => response.json())
.then(json => {
    alert('Found ' + result.data.allPosts.length + ' posts');
})

Adding Authentication, Custom Routes, etc.

json-graphql-server doesn't deal with authentication or custom routes. But you can use your favorite middleware with Express:

import express from 'express';
import jsonGraphqlExpress from 'json-graphql-server';

import OAuthSecurityMiddleWare from './path/to/OAuthSecurityMiddleWare';

const PORT = 3000;
const app = express();
const data = {
    // ... your data
};
app.use(OAuthSecurityMiddleWare());
app.use('/graphql', jsonGraphqlExpress(data));
app.listen(PORT);

Schema Export

You can also use the export jsonSchemaBuilder to get your own copy of the GraphQLSchema:

In node:

import {graphql} from 'graphql';
import {jsonSchemaBuilder} from 'json-graphql-server';

const data = { };
const schema = jsonSchemaBuilder(data);
const query = `[...]`

graphql(schema, query).then(result => {
  console.log(result);
});

Or available in the global scope when running on a client as jsonSchemaBuilder.

Plain Schema

If you want to use another server type instead of the built in graphql express, like apollo-server or etc, you can expose the plain schema to be built into an executable schema (there may be version issues otherwise).

This uses the export getPlainSchema.

import { ApolloServer } from 'apollo-server';
import { makeExecutableSchema } from '@graphql-tools/schema'; // or graphql-tools
import { applyMiddleware } from 'graphql-middleware';
import { getPlainSchema } from 'json-graphql-server';

const data = { };

// Example middlewares
const logInput = async (resolve, root, args, context, info) => {
    console.log(`1. logInput: ${JSON.stringify(args)}`);
    const result = await resolve(root, args, context, info);
    console.log(`5. logInput`);
    return result;
};
const logResult = async (resolve, root, args, context, info) => {
    console.log(`2. logResult`);
    const result = await resolve(root, args, context, info);
    console.log(`4. logResult: ${JSON.stringify(result)}`);
    return result;
};

// Leverage getPlainSchema
const schema = applyMiddleware(
    makeExecutableSchema(getPlainSchema(data)),
    logInput,
    logResult
);
const server = new ApolloServer({
    schema,
});
server.listen({ port: 3000 });

Deployment

Deploy with Heroku or Next.js.

Roadmap

  • CLI options (https, watch, delay, custom schema)
  • Subscriptions
  • Client-side mocking (à la FakeRest)

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

To learn more about the contributions to this project, consult the contribution guide.

Maintainers

fzaninotto djhi alexisjanvier
Francois Zaninotto Gildas Garcia Alexis Janvier

License

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

More Repositories

1

react-admin

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design
TypeScript
22,823
star
2

gremlins.js

Monkey testing library for web apps and Node.js
JavaScript
8,971
star
3

ng-admin

Add an AngularJS admin GUI to any RESTful API
JavaScript
3,968
star
4

awesome-rest

A collaborative list of great resources about RESTful API architecture, development, test, and performance
3,457
star
5

universal.css

The only CSS you will ever need
CSS
1,260
star
6

EventDrops

A time based / event series interactive visualization using d3.js
JavaScript
1,236
star
7

restful.js

A pure JS client for interacting with server-side RESTful resources. Think Restangular without Angular.
JavaScript
969
star
8

gaudi

Gaudi allows to share multi-component applications, based on Docker, Go, and YAML.
Go
566
star
9

ng-admin-react

Add a ReactJS admin GUI to any RESTful API. Deprecated: see admin-on-rest for a full rewrite
JavaScript
544
star
10

FakeRest

Patch fetch/XMLHttpRequest to fake a REST API server in the browser, based on JSON data.
JavaScript
407
star
11

admin-on-rest

A frontend framework for building admin SPAs on top of REST services, using React and Material Design.
JavaScript
400
star
12

admin-on-rest-demo

Source of the admin-on-rest react.js demo, using a dummy REST service powered by FakeRest
JavaScript
329
star
13

ng-admin-demo

Source of the ng-admin angular.js demo, using a dummy REST service powered by FakeRest
JavaScript
305
star
14

sedy

A GitHub bot bringing the sed command to code reviews
JavaScript
266
star
15

javascript-boilerplate

Node.js+Koa.js+PostgreSQL+React.js+Webpack+Mocha+Makefile, a starter kit for new apps
JavaScript
253
star
16

ArchitectureTree

Draw and share your software architecture without diagramming software. Uses d3.js and Angular.js.
JavaScript
218
star
17

comfygure

Encrypted and versioned configuration store built with collaboration in mind
JavaScript
192
star
18

microrest.php

A micro web application providing a REST API on top of any relational database, using Silex and Doctrine DBAL
PHP
186
star
19

graphql-schema-from-json

Guess a GraphQL schema from json data
JavaScript
184
star
20

tree.js

Tree.js is a JavaScript library to build and manipulate hookable trees.
JavaScript
148
star
21

greenframe-cli

Estimate the carbon footprint of a user scenario on a web application
TypeScript
137
star
22

ra-supabase

Supabase adapter for react-admin, the frontend framework for building admin applications on top of REST/GraphQL services.
TypeScript
127
star
23

ng-admin-postgrest

Demo of an integration between ng-admin and PostgREST
JavaScript
111
star
24

phpcr-browser

Web interface for browsing PHPCR repositories, using Silex and AngularJS
CSS
103
star
25

sketch-by-phone

A proof-of-concept of Augmented Reality with HTML5
JavaScript
97
star
26

ArcheoloGit

Where should you focus the maintenance efforts? ArcheoloGit is a visualization of age and dev activity for software, powered by d3.js.
JavaScript
95
star
27

phpunit-d3-report

Visualize the slowest parts of a PHPUnit testsuite using d3.js
JavaScript
93
star
28

GraphQL-example

An example code structure for a GraphQL-powered mobile app. Contains client and server code.
JavaScript
86
star
29

make-docker-command

Seamlessly execute commands (composer, bower, compass) in isolation using docker and make.
Makefile
83
star
30

aor-graphql

Packages related to using GraphQL with Admin-on-rest
JavaScript
81
star
31

react-admin-demo

Source of the react-admin react.js demo, using a dummy REST service powered by FakeRest
67
star
32

ra-auth-acl

Access Control List authProvider and helpers for React Admin
TypeScript
64
star
33

aor-dependent-input

A component for displaying input depending on other inputs values in Admin-on-rest
JavaScript
60
star
34

argos

docker monitoring experiment
58
star
35

react-md-motion

Material design motions with react
JavaScript
54
star
36

Raphael.InlineTextEditing

Raphael Plugin allowing inline edition of SVG text elements
JavaScript
54
star
37

ra-example-oauth

An example of OpenID Connect implementation on React Admin
TypeScript
53
star
38

aor-simple-graphql-client

A simple GraphQL client for admin-on-rest
JavaScript
48
star
39

ZeroDollarHomePage

A decentralized ad server running on the blockchain
JavaScript
45
star
40

SonataElasticaBundle

Power the Sonata Admin list view and filters by an ElasticSearch index to speed up navigation.
PHP
43
star
41

aor-permissions

A component for Admin-on-rest allowing to switch views depending on user permissions. Eg: having different PostEdit components for different users
JavaScript
42
star
42

react-admin-crm

A CRM build with react-admin, used as a demo for the capabilities of the framework
HTML
40
star
43

ra-in-memory-jwt

Manage React-admin authentication with jwt in memory, not in local storage
JavaScript
39
star
44

koa-multifetch

A Koa.js middleware for performing internal batch requests
JavaScript
36
star
45

gollabedit

Experimental collaborative editor written in Go
Go
33
star
46

admin-config

Configuration API to describe an administration interface. Used by ng-admin and react-admin.
JavaScript
31
star
47

ocaml-invader

Ocaml Space-Invader implementation using OpenGL
OCaml
29
star
48

admin-on-rest-graphql-demo

JavaScript
29
star
49

ra-data-google-sheets

A data provider for react-admin, based on Google Sheets
JavaScript
26
star
50

ra-datagrid

Integration of Material-ui's <Datagrid> into react-admin
TypeScript
26
star
51

battery-friendly-timer

Mobile applications using setInterval to poll a server are a battery hogs. Save battery life by fetching data at the right moment.
JavaScript
25
star
52

MobileInsight

A Mobile web app to browse PHP code analyses made by SensioLabsInsight, built with Angular.js and Ionic.
JavaScript
25
star
53

yolo

Typo-tolerant runtime object proxy for fast JavaScritp typers
JavaScript
24
star
54

aor-rich-text-input

<RichTextInput> component for admin-on-rest, useful for editing HTML code in admin GUIs
CSS
23
star
55

timeline-react-admin

Support for a tutorial about custom List views with react-admin
JavaScript
23
star
56

strapi-beerdex

StrapiJS Example Application For Beer Management
JavaScript
23
star
57

chrome-bug-report-wizard

Chrome plugin automating Bug Tracker issue creation with screenshot and browser details
JavaScript
23
star
58

argos-cli

19
star
59

aor-realtime

JavaScript
17
star
60

solid-admin

TypeScript
17
star
61

ra-enterprise-demo

TypeScript
16
star
62

svelte-sse-chat

Chat Example Application Using SvelteJS and Chat
Svelte
15
star
63

uptime

A prototype of website monitoring tool, written in Go and React.js, modeled after fzaninotto/uptime
JavaScript
15
star
64

reactive-beers

Reactive Beers is an example application using CouchDB and PouchDB
JavaScript
15
star
65

reversi-reason

🐪 ReasonML implementation of Reversi Game
OCaml
13
star
66

MobileAudience

Mobile Webapp mixing D3.js with a touch UI ; shows TV audiences and market shares for 8 fictive TV channels across several days.
JavaScript
13
star
67

ng-tree

An Angular.js module for using tree.js
JavaScript
12
star
68

docker-parallel-phpunit-demo

How to use Docker to run PHPUnit tests in parallel
PHP
12
star
69

skelt

{ } Skelt is a simple templating engine for object literals.
JavaScript
12
star
70

redux-form-inspector

An HOC for computing dynamic props from values inside an existing redux-form component.
JavaScript
12
star
71

virothello

💫 Othello Game Using Augmented Reality And Viro
JavaScript
12
star
72

coPostgresQuery

Query builder for PostgreSQL in Node.js, built for async
JavaScript
11
star
73

phpcr-api

PHP
11
star
74

svg_to_png

Convert an SVG file to a PNG image. Uses headless Chrome for rendering.
JavaScript
11
star
75

aor-json-rest-client

A local REST client for admin-on-rest
JavaScript
10
star
76

ra-keycloak

TypeScript
10
star
77

docker-compass

Dockerfile
10
star
78

curator-ai

An AI-powered news curator. It reads a list of articles, selects the best ones depending on a list of interests, and summarizes them into an easy-to-read news feed. Powered by the OpenAI API.
TypeScript
10
star
79

dobble

Generate a valid deck of cards for Dobble in ECMAScript6
JavaScript
10
star
80

ra-sqlite-dataprovider

POC of a dataprovider using a sqlite database hosted on a static server
JavaScript
9
star
81

checkoid

Experimental validator library allowing to combine validator like you would lego piece.
TypeScript
9
star
82

gql-profiler

A standalone performance profiler for GraphQL resolvers
JavaScript
9
star
83

liMonade

A Monad library to make Monad simple.
TypeScript
9
star
84

dedale

A wood labyrinth game in the browser
JavaScript
9
star
85

silex-multifetch

A Silex provider for performing internal batch requests
PHP
9
star
86

treedu

Graphical Disk Usage command for the terminal, using Node.js, d3.js, blessed, and Drawille
JavaScript
9
star
87

ra-auth-cognito

An auth provider for [react-admin](https://github.com/marmelab/react-admin) which handles authentication with AWS [Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html).
TypeScript
9
star
88

docker-composer-hhvm

8
star
89

Asteroids.js

A one day experiment to bringing the Asteroids game to the browser, using a mobile device as controller, Node.js, Raphaël, and socket.io.
JavaScript
8
star
90

docker-bower

Dockerfile
8
star
91

next-react-admin

TypeScript
8
star
92

ra-richtext-tiptap

TypeScript
7
star
93

puppeteer-accessibility

JavaScript
7
star
94

web-myna

Record then emulate your api.s for testing and development
JavaScript
7
star
95

ninja-coder

Code with your entire body like a Ninja
JavaScript
7
star
96

configurable.js

A small JS snippet to make a function configurable through its closure
JavaScript
7
star
97

gif-to-webm

Convert GIF files to WebM and replace links to them in doc files
TypeScript
6
star
98

sg

Side Effect Handling library - Think Redux-Saga without Redux
JavaScript
6
star
99

selenium-smart-wait

JavaScript
6
star
100

dobble-php

PHP
6
star