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

posted on   荣锋亮  阅读(249)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示