graphql入门

2019-06-16  本文已影响0人  zxhnext

我们新建一个app.js

import koa from 'koa'; // koa@2 
import koaRouter from 'koa-router'; // koa-router@next 
import koaBody from 'koa-bodyparser'; // koa-bodyparser@next 
import { graphqlKoa } from 'graphql-server-koa'; // apollo
import render from 'koa-swig';
import co from 'co';
import serve from 'koa-static';
import { graphql, GraphQLSchema,GraphQLObjectType, GraphQLString,GraphQLInt } from 'graphql';
 //数据
 const data ={
  "1": {
    "id": "1",
    "name": "一号老王",
    "age":23
  },
  "2": {
    "id": "2",
    "name": "二号老袁",
    "age":18
  },
  "3": {
    "id": "3",
    "name": "三号老方",
    "age":20
  }
};
const userType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    age:{ type: GraphQLInt }
  }
});
const myGraphQLSchema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      user: {
        type: userType,
        // `args` describes the arguments that the `user` query accepts
        args: {
          id: { type: GraphQLString }
        },
        // The resolve function describes how to "resolve" or fulfill
        // the incoming query.
        // In this case we use the `id` argument from above as a key
        // to get the User from `data`
        resolve: function (_, args) {
          return data[args.id];
        }
      }
    }
  })
});

const app = new koa();
const router = new koaRouter();
const PORT = 3000;
app.use(serve('./')); // 静态资源文件
 app.context.render = co.wrap(render({
    root: './',
    autoescape: true,
    cache: 'memory', // disable, set to false
    ext: 'html',
    varControls: ['[[', ']]'],
    writeBody: false
}));
// koaBody is needed just for POST. 
app.use(koaBody());
router.post('/graphql', graphqlKoa({ schema: myGraphQLSchema }));
router.get('/graphql', graphqlKoa({ schema: myGraphQLSchema }));
router.get('/index', async ctx => ctx.body = await ctx.render('index'));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(PORT);

前端发起请求:

import Lokka from 'lokka';
import Transport from 'lokka-transport-http';
const client = new Lokka({
  transport: new Transport('http://localhost:3000/graphql')
});
const dataInfo = client.createFragment(`
  fragment on User {
    name,
    age
  }
`);

client.query(`
    {
        user(id:"2") {
          name
        }
    }
`).then(result => {
    console.log(result);
});

关注apollo-server-koa插件

上一篇 下一篇

猜你喜欢

热点阅读