码迷,mamicode.com
首页 > Windows程序 > 详细

swagger api 转graphql npm 包试用

时间:2018-07-27 12:13:31      阅读:477      评论:0      收藏:0      [点我收藏+]

标签:asi   host   测试   data-   访问   镜像   yar   express   OLE   

graphql 比较方便的进行api 的查询,操作,swagger 是一个方便的open api 描述标准,当前我们有比较多的
restapi 但是转换为graphql 是有成本的,还好swagger-to-graphql 这个npm 包帮助我们简化了操作

基本项目

具体项目参考 https://github.com/rongfengliang/swagger-to-graphql-docker

  • 项目结构
├── Dockerfile
├── README.md
├── api
│ └── s.json
├── app.js
├── docker-compose.yaml
├── lib
│ ├── index.js
│ ├── swagger.js
│ ├── typeMap.js
│ └── types.js
├── package.json
└── yarn.lock
  • 代码说明
package.json  依赖添加
{
  "name": "swagger-graphql",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "express": "^4.16.3",
    "express-graphql": "^0.6.12",
    "graphql": "^0.13.2",
    "swagger-to-graphql": "^1.4.0"
  },
  "scripts": {
    "start": "node app"
  }
}
app.js restapi 转 graphql 
require(‘babel-polyfill‘);
const express = require(‘express‘);
const app = express();
const graphqlHTTP = require(‘express-graphql‘);
const graphQLSchema = require(‘./lib‘); // 类型映射

const proxyUrl = ‘https://petstore.swagger.io/v2‘;
const pathToSwaggerSchema = `${__dirname}/api/s.json`; // swagger api 描述
const customHeaders = {
  Authorization: ‘Basic YWRkOmJhc2ljQXV0aA==‘
};

graphQLSchema(pathToSwaggerSchema, proxyUrl, customHeaders).then(schema => {
  app.use(‘/graphql‘, graphqlHTTP(() => {
    return {
      schema,
      graphiql: true
    };
  }));

  app.listen(3009, ‘0.0.0.0‘, () => {
    console.info(‘http://localhost:3009/graphql‘);
  });
}).catch(e => {
  console.log(e);
});

Dockerfile  docker 镜像构建

FROM dalongrong/node-yarn
WORKDIR /app
COPY . /app
RUN yarn install
EXPOSE 3009
ENTRYPOINT [ "yarn","start" ]

docker-compose.yaml  docker-compose 运行文件
version: "3"
services:
   g:
    build: ./
    image: dalongrong/swagger-graphql
    ports:
    - "3009:3009"

运行

  • docker 镜像构建
docker-compose build
  • docker-compose run
docker-compose up -d
  • 访问
    请求测试
    技术分享图片
    接口文档
    技术分享图片

说明

类似的解决方案有 schema stitch graphql-binding

参考资料

https://github.com/yarax/swagger-to-graphql
https://github.com/graphql-binding/graphql-binding
https://www.prisma.io/blog/reusing-and-composing-graphql-apis-with-graphql-bindings-80a4aa37cff5/
https://github.com/rongfengliang/swagger-to-graphql-docker

swagger api 转graphql npm 包试用

标签:asi   host   测试   data-   访问   镜像   yar   express   OLE   

原文地址:https://www.cnblogs.com/rongfengliang/p/9376446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!