importgetSchemaFromDatafrom'graphql-schema-from-json';import{printSchema}from'graphql';constdata={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: newDate('2017-07-03')},{id: 995,post_id: 1,body: "Nam molestie pellentesque dui",date: newDate('2017-08-17')}]}// Get the schema as a JSON objectconstschema=getSchemaFromData(data);// Print the GQL for this schemaconsole.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:
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
}
}
请发表评论