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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.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