graphql-yoga interface && union 使用
Posted rongfengliang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了graphql-yoga interface && union 使用相关的知识,希望对你有一定的参考价值。
接口就是一个约定,方便数据的约定,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
以上是关于graphql-yoga interface && union 使用的主要内容,如果未能解决你的问题,请参考以下文章
在 graphql-yoga 中返回枚举的解析器函数是啥样的?
使用 Mongoose 和 graphql-yoga 实现分页
无法通过 Prisma 在 GraphQL-yoga 中使用片段
graphql-yoga - GraphQL 解析器参数在哪里定义和记录?