graphql-binding openapi 集成demo

相似的將openapi 轉換爲graphql api 的也有 https://github.com/yarax/swagger-to-graphqlnode

基本項目

參考代碼 https://github.com/rongfengliang/graphql-binding-openapi-dockergit

  • 項目結構
├── Dockerfile
├── README.md
├── app.js
├── docker-compose.yaml
├── images
│ └── info.png
├── package.json
├── petstore.graphql
├── petstore.json
└── yarn.lock
  • 代碼說明

    集成graphql-yogagithub

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-openapidocker

相關文章
相關標籤/搜索