swagger api 转graphql npm 包试用

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

 
 
 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值