apollo-server-koa 简单使用

前端之家收集整理的这篇文章主要介绍了apollo-server-koa 简单使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

server.js

  1. import koa from 'koa'; // koa@2 npm install --save koa@2
  2. import koaRouter from 'koa-router'; // koa-router@next
  3. import koaBody from 'koa-bodyparser'; // koa-bodyparser@next
  4. import { graphqlKoa,graphiqlKoa } from 'apollo-server-koa';
  5. import schema from './src/graphql/schema.js';
  6. import executableSchema from './src/graphql/executableSchema';
  7.  
  8. const app = new koa();
  9. const router = new koaRouter();
  10. const PORT = 3000;
  11.  
  12. // koaBody is needed just for POST.
  13. router.post('/graphql',koaBody(),graphqlKoa({ schema: executableSchema }));
  14. router.get('/graphql',graphqlKoa({ schema: executableSchema }));
  15.  
  16. router.get('/graphiql',graphiqlKoa({ endpointURL: '/graphql' }));
  17.  
  18. app.use(router.routes());
  19. app.use(router.allowedMethods());
  20. app.listen(PORT,()=>console.log(`localhost:${PORT}`));

package.json


  1. {
  2. "name": "mcbeath","version": "1.0.0","description": "my mcbeath network","main": "index.js","scripts": {
  3. "test": "echo \"Error: no test specified\" && exit 1","start": "babel-node server.js"
  4. },"author": "","license": "MIT","dependencies": {
  5. "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"
  6. }
  7. }

必备文件说明

apollo-server-koa:apollo graphql服务
babel-cli:是一个工具,可以帮助你在JavaScript的最新版本编写代码。当你的环境支持不支持某些功能本身,Babel会帮助你编译的功能到一个支持的版本。
babel-preset-env:babel的环境变量,可以支持你的浏览器
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配置 (必不可少否则最新语法无法编译)

  1. {
  2. "presets": [
  3. ["env",{
  4. "targets": {
  5. "node": true
  6. }
  7. }]
  8. ]
  9. }

猜你在找的React相关文章