graphql-yoga 項目簡單使用&&集成docker


graphql-yoga 是一個實現了grahql的框架,使用簡單,便捷
具體源碼參考github https://github.com/rongfengliang/graphql-yoga-dockerdemo

安裝框架

  • yarn
yarn init -y 
yarn add graphql-yoga

項目結構

項目包好了docker jenkins docker-compose && 基本graphql-yoga demo

├── Jenkinsfile
├── README.md
├── app.js
├── docker-compose.yml
├── dockerfile
├── images
│ ├── 1.png
│ └── 2.png
├── package.json
├── schema.graphql
└── yarn.lock

代碼說明

  • Jenkinsfile

    jenkins pipeline 集成,比較簡單

pipeline {
agent {
node {
label 'jt68'
}
}
stages {
stage('image build') {
steps {
sh 'docker-compose build'
}
}
stage('docker-compose run') {
steps {
sh 'docker-compose stop && docker-compose up -d '
}
}
}
}
  • app.js

    query && mutation 的實現

const { GraphQLServer } = require('graphql-yoga')
const typeDefs = `schema.graphql`
const resolvers = {
Query: {
hello: function(_,name){
return {
name:`${name.name}`,
age:33
}
},
localtype:function(parent,ob){
return {
name:`${ob.name}`,
age: ob.name.length
}
},
listOfStrings:function(parent){
return [
"dalong",
"demoapp",
"rong"
]
}
},
Mutation:{
addUser:function(parent,ob){
console.log(ob)
return JSON.stringify(ob)
}
}
}
const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000'))
  • docker-compose.yml

    docker-compose 集成

version: "3"
services:
api:
image: graphql-api
build: .
ports:
- "4000:4000"
  • dockerfile

    docker 集成代碼,實際可以修改不通的基礎鏡像,這個因為當時測試網路的問題,直接copy node module

FROM dalongrong/node-yarn:9
WORKDIR /app
COPY . /app
RUN yarn config set registry https://registry.npm.taobao.org
ENTRYPOINT [ "yarn","start" ]
  • schema.graphql

    graphql schema && query && mutation 定義

type LocalUser {
name: String
age: Int
}
interface Applogin {
name:String
account:String
}
type MobileApplogin implements Applogin{
type:Int
name:String
account:String
}

# input 對象
input MyUser {
name:String
age:Int
}
# 查詢定義
type Query {
hello(name: String): User!
localtype(name:String):LocalUser!
listOfStrings: [String]!
}
# 數據添加定義
type Mutation{
addUser(input:MyUser):String
}
# 數據類型定義,參考下面的query 截圖
scalar User {
name: String
age: Int
}

測試使用

  • 啟動
yarn start  or  docker-compose build && docker-compose up -d
  • query a (return saclar 對象)
  • query b 基本對象
  • mutation (使用input)
  • directvie add

參考資料

https://github.com/prismagraphql/graphql-yoga
https://github.com/rongfengliang/graphql-yoga-dockerdemo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM