GraphQL API In Action
GraphQL API
express
$ yarn add express express-graphql graphql
# OR
$ npm i -S express express-graphql graphql
https://github.com/graphql/express-graphql
https://www.npmjs.com/package/express-graphql
express-graphq
https://graphql.org/graphql-js/express-graphql/
// import graphqlHTTP from 'express-graphql';
// ES6
// const graphqlHTTP = require('express-graphql');
// CommonJS
// ❓❓❓default modue
import { graphqlHTTP } from 'express-graphql';
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// graphqlHTTP
graphqlHTTP({
schema: GraphQLSchema,
graphiql?: ?boolean,
rootValue?: ?any,
context?: ?any,
pretty?: ?boolean,
formatError?: ?Function,
validationRules?: ?Array<any>,
}): Middleware
demos
https://graphql.org/graphql-js/running-an-express-graphql-server/
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-0
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
*/
const log = console.log;
// server.js
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
const root = {
hello: () => {
return 'Hello world!';
},
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,// graphiql
}));
app.listen(8888);
console.log('Running a GraphQL API server at http://localhost:8888/graphql');
graphiql: true,
query
query{
hello,
}
// OR
{
hello,
}
result
{
"data": {
"hello": "Hello world!"
}
}
refs
GraphQL Landscape
https://www.youtube.com/watch?v=g2LbFPAKQZk
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!