码迷,mamicode.com
首页 > 其他好文 > 详细

创建自定义graphql-binding

时间:2018-08-11 01:23:40      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:create   str   step   bottom   end   exp   host   exe   graphql   

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/

创建自定义graphql-binding

标签:create   str   step   bottom   end   exp   host   exe   graphql   

原文地址:https://www.cnblogs.com/rongfengliang/p/9457952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!