apollo-server-koa 简单使用

server.js

import koa from 'koa'; // koa@2   npm install --save koa@2
import koaRouter from 'koa-router'; // koa-router@next
import koaBody from 'koa-bodyparser'; // koa-bodyparser@next
import { graphqlKoa,graphiqlKoa } from 'apollo-server-koa';
import schema from './src/graphql/schema.js';
import executableSchema from './src/graphql/executableSchema';

const app = new koa();
const router = new koaRouter();
const PORT = 3000;

// koaBody is needed just for POST.
router.post('/graphql',koaBody(),graphqlKoa({ schema: executableSchema }));
router.get('/graphql',graphqlKoa({ schema: executableSchema }));

router.get('/graphiql',graphiqlKoa({ endpointURL: '/graphql' }));

app.use(router.routes());
app.use(router.allowedMethods());
app.listen(PORT,()=>console.log(`localhost:${PORT}`));

package.json


{
  "name": "mcbeath","version": "1.0.0","description": "my mcbeath network","main": "index.js","scripts": {
    "test": "echo \"Error: no test specified\" && exit 1","start": "babel-node server.js"
  },"author": "","license": "MIT","dependencies": {
    "apollo-server-koa": "^1.1.2","babel-cli": "^6.26.0","babel-preset-env": "^1.6.0","graphql": "^0.11.5","koa": "^2.3.0","koa-bodyparser": "^3.2.0","koa-router": "^7.1.1"
  }
}

必备文件说明

apollo-server-koa:apollo graphql服务
babel-cli:一个工具,可以帮助你在JavaScript的最新版本编写代码。当你的环境支持不支持某些功能本身,Babel会帮助你编译的功能一个支持的版本。
babel-preset-envbabel的环境变量,可以支持你的浏览器
graphql: The GraphQL specification is edited in the markdown files found in /spec the latest release of which is published at http://facebook.github.io/graphql/ .
koa中间件使用异步函数表达es2017
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner,allowing you to perform actions downstream then filter and manipulate the response upstream.
koa-bodyparser:A body parser for koa,base on co-body. support json,form and text type body.
koa-router:Router middleware forkoa

.babelrc配置 (必不可少否则最新语法无法编译)

{
  "presets": [
    ["env",{
      "targets": {
        "node": true
      }
    }]
  ]
}

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...