创建自定义graphql-binding

graphql-binding 是一个比较方便强大的工具,方便我们进行代码生成以及开发gateway的功能

项目初始化

  • 使用prisma cli

    使用脚手架

prisma init appdemo
? Set up a new Prisma server or deploy to an existing server? Use existing database
? What kind of database do you want to deploy to? (Use arrow keys)
❯ MySQL MySQL compliant databases like MySQL or MariaDB
  PostgreSQL PostgreSQL database
➜ binding prisma init appdemo
? Set up a new Prisma server or deploy to an existing server? Create new database
? What kind of database do you want to deploy to? MySQL

Created 3 new files:

  prisma.yml Prisma service definition
  datamodel.graphql GraphQL SDL-based datamodel (foundation for database)
  docker-compose.yml Docker configuration file

Next steps:

  1. Open folder: cd appdemo
  2. Start your Prisma server: docker-compose up -d
  3. Deploy your Prisma service: prisma deploy
  4. Read more about Prisma server:
     http://bit.ly/prisma-server-overview
  • 添加数据
mutation {
  createUser(data:{
    name:"demoapp"
  }){
    id
    name
  }
}

创建bingding

  • 生成schema
npm install -g get-graphql-schema
get-graphql-schema http://localhost:4466 > myuser-graphql-binding/schemas/datamodel.graphql
  • 添加依赖
{
"name": "myuser-graphql-binding",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"apollo-link-http": "^1.5.4",
"fs": "^0.0.1-security",
"graphql": "^0.13.2",
"graphql-binding": "^2.2.2",
"node-fetch": "^2.2.0"
}
}
  • 添加bingding代码
const fs = require('fs')
const path = require('path')
const fetch = require('node-fetch')
const { Binding } = require('graphql-binding')
const { HttpLink } = require('apollo-link-http')
const { makeRemoteExecutableSchema } = require('graphql-tools')

const link = new HttpLink({ uri: 'http://localhost:4466', fetch })
const typeDefs = fs.readFileSync(
path.join(__dirname, './schemas/datamodel.graphql'),
'utf-8',
)
const schema = makeRemoteExecutableSchema({ link, schema: typeDefs })
class MyUserBinding extends Binding {
constructor() {
super({ schema })
}
}
module.exports = MyUserBinding

使用

  • 使用npm link 生成local package
npm link myuser-graphql-binding
  • 调用
app.js
const binding = require("myuser-graphql-binding")
const post_api = new binding();
console.log(post_api.query.users({}).then((data)=>{
console.log(data)
}))

参考图


参考资料

https://www.prisma.io/blog/graphql-binding-2-0-improved-api-schema-transforms-automatic-codegen-5934cd039db1/
https://github.com/rongfengliang/graphql-bingding-demo
https://docs-beta.prisma.io/1.13/use-prisma-api/prisma-bindings/code-generation-frr1/

posted on 2018-08-10 23:14  荣锋亮  阅读(235)  评论(0编辑  收藏  举报

导航