接口就是一个约定,方便数据的约定,union 可以实现数据类型的共享,减少代码量
基本项目
参考 https://github.com/rongfengliang/graphql-yoga-dockerdemo
- 项目结构
├── Jenkinsfile
├── README.md
├── app.js
├── docker-compose.yml
├── dockerfile
├── package.json
├── schema.graphql
└── yarn.lock
interface && union 使用
- interface app.js
const { GraphQLServer } = require('graphql-yoga')
const typeDefs = `schema.graphql`
const resolvers = {
Applogin:{
__resolveType(obj) {
if (obj.type==1) {
return 'MobileApplogin'
} else {
return 'DesktopApplogin'
}
}
},
SearchResult:{
__resolveType(obj) {
if (obj.type) {
return 'App'
} else {
return 'LocalUser'
}
}
},
Query: {
hello: function(_,name){
return {
name:`${name.name}`,
age:33
}
},
localtype:function(parent,ob){
return {
name:`${ob.name}`,
age: ob.name.length
}
},
login:function(parent,ob){
if (ob.name=="dalong"){
return {
name:"dalong",
account:"app mobile info"
}
}
else {
return {
name:"dalong",
type:44,
account:"app mobile info"
}
}
},
appsearch:function(parent,ob){
return {
name:"demoaopp",
age:333,
type:55
}
},
appinfo:function(parent,ob){
console.log(ob,parent)
return {
name:ob.name,
type:3
}
},
listOfStrings:function(parent){
return [
"dalong",
"demoapp",
"rong"
]
}
},
Mutation:{
addUser:function(parent,ob){
console.log(ob)
return JSON.stringify(ob)
}
}
}
const options = {
port: 8000,
endpoint: '/graphql',
subscriptions: '/subscriptions',
playground: '/playground',
}
const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000'))
- schema
type LocalUser {
name: String
age: Int
}
interface Applogin {
name:String
account:String
}
type MobileApplogin implements Applogin{
type:Int
name:String
account:String
}
type DesktopApplogin implements Applogin{
type:Int
name:String
account:String
}
union SearchResult = App|LocalUser
input MyUser {
name:String
age:Int
}
type Query {
hello(name: String): User!
localtype(name:String):LocalUser!
listOfStrings: [String]!
# interface demo
login(name:String):Applogin
# for directive demo
appinfo(name:String,flag:Boolean):App
# union demo
appsearch(name:String):SearchResult
}
# app info
type App {
# app name
name:String
# app type
type:Int
}
type Mutation{
addUser(input:MyUser):String
}
scalar User {
name: String
age: Int
}
参考效果
- interface
- union
参考资料
https://github.com/rongfengliang/graphql-yoga-dockerdemo
http://graphql.cn/learn/schema/#interfaces