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

posted on   荣锋亮  阅读(1087)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2015-06-26 Why we made vorlon.js and how to use it to debug your JavaScript remotely

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示