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

猜你喜欢

转载自www.cnblogs.com/rongfengliang/p/9376446.html