graphql-binding openapi 集成demo
类似的将openapi 转换为graphql api 的也有 https://github.com/yarax/swagger-to-graphql
基本项目
参考代码 https://github.com/rongfengliang/graphql-binding-openapi-docker
- 项目结构
├── Dockerfile
├── README.md
├── app.js
├── docker-compose.yaml
├── images
│ └── info.png
├── package.json
├── petstore.graphql
├── petstore.json
└── yarn.lock
- 代码说明
集成graphql-yoga
package.json
{
"name": "open-api",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"graphql-binding-openapi": "^1.0.5",
"graphql-import": "^0.6.0",
"graphql-yoga": "^1.16.0"
},
"scripts": {
"start":"node app"
}
}
petstore.json openapi 接口说明
petstore.graphql 接口graphql schema
app.js: 集成模块
const { OpenApi } = require('graphql-binding-openapi')
const { GraphQLServer } = require('graphql-yoga')
const {importSchema} = require("graphql-import")
const typeDefs = importSchema("./petstore.graphql")
const resolvers = {
Query: {
findPetsByStatus: async (parent, args, context, info) => {
return context.petstore.query.findPetsByStatus({ status: "available" }, context, info)
}
}
}
const server = new GraphQLServer({
resolvers,
typeDefs,
context: async req => ({
...req,
petstore: await OpenApi.init('./petstore.json', 'http://petstore.swagger.io/v2')
})
});
server.start(() => console.log('Server running on http://localhost:4000'))
运行
- 本地
yarn start
- 效果
- docker
docker-compose build
docker-compose up -d
说明
从使用的方便上来说swagger-to-graphql 似乎更简单,不需要schema 编写,同时提供了一个cli
使用以来命令帮助我们生成schema
swagger-to-graphql --swagger=/path/to/swagger_schema.json > ./types.graphql,结合起来使用可能
会更方便。
参考资料
https://github.com/rongfengliang/graphql-binding-openapi-docker
https://github.com/graphql-binding/graphql-binding-openapi