在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:marmelab/json-graphql-server开源软件地址:https://github.com/marmelab/json-graphql-server开源编程语言:JavaScript 99.7%开源软件介绍:json-graphql-serverGet a full fake GraphQL API with zero coding in less than 30 seconds. Motivation
Start playing with GraphQL right away with Inspired by the excellent json-server. ExampleFollow the guide below starting from scratch, or see the example live on StackBlitz: Create a 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 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 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 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. Installnpm install -g json-graphql-server Generated Types and QueriesBased 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 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 For every field named The Supported types
GraphQL UsageHere is how you can use the queries and mutations generated for your data, using
Usage with NodeInstall the module locally: npm install --save-dev json-graphql-server Then use the 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 XMLHttpRequestUseful when using XMLHttpRequest directly or libraries such as axios. Install with a script tagAdd a <script src="../lib/json-graphql-server.client.min.js"></script> It will expose the <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 fetchimport 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.
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 ExportYou can also use the export 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 Plain SchemaIf 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 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
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论