Graphql Typecheck on redux like events
Graphql Typecheck on redux like events
我正在使用 apollo-server 在一些现有的 REST api 上实现一个 graphql 服务器。
有一个端点返回一个类似 redux 的事件列表,其中 Hi 有一个 type
和一个 payload
。
type
是一个字符串,payload
是一个对象。例如
[
{
type:"joined"
from:"member1"
payload:{
received_events:"1518377870416"
invited_by:"member2"
}
},
{
type:"text"
from:"member1"
payload:{
test_string:"hello"
}
}
]
我需要检查的是:
1) type
是枚举 joined|text
2) from
是一个字符串
3) if type == joined
then payload
should contain received_events
and invited_by
, if type == text
then payload
should contain test_string
最好的方法是什么?我正在查看 scalar 和 Union,但我不确定该怎么做。
解决此问题的一种方法是将事件类型中的类型注入到有效负载对象中。然后可以在联合的 __resolveType
解析器中使用它。一个简单的例子:
const typeDefs = `
type Query {
events: [Event]
}
type Event {
type: String
payload: Payload
}
union Payload = Text | Joined
type Text {
test_string: String
}
type Joined {
received_events: String
invited_by: String
}
`;
// Since your type names and the specified types are different, we
// need to map them (resolveType needs to return the exact name)
const typesMap = {
text: 'Text',
joined: 'Joined'
}
const resolvers = {
Query: {
events: (root, args, context) => {
return [
{ type: 'text', payload: { test_string: 'Foo' } }
];
},
},
// We can use the resolver for the payload field to inject the type
// from the parent object into the payload object
Event: {
payload: (obj) => Object.assign({ type: obj.type }, obj.payload)
},
// The type can then be referenced inside resolveType
Payload: {
__resolveType: (obj) => typesMap[obj.type]
}
};
我正在使用 apollo-server 在一些现有的 REST api 上实现一个 graphql 服务器。
有一个端点返回一个类似 redux 的事件列表,其中 Hi 有一个 type
和一个 payload
。
type
是一个字符串,payload
是一个对象。例如
[
{
type:"joined"
from:"member1"
payload:{
received_events:"1518377870416"
invited_by:"member2"
}
},
{
type:"text"
from:"member1"
payload:{
test_string:"hello"
}
}
]
我需要检查的是:
1) type
是枚举 joined|text
2) from
是一个字符串
3) if type == joined
then payload
should contain received_events
and invited_by
, if type == text
then payload
should contain test_string
最好的方法是什么?我正在查看 scalar 和 Union,但我不确定该怎么做。
解决此问题的一种方法是将事件类型中的类型注入到有效负载对象中。然后可以在联合的 __resolveType
解析器中使用它。一个简单的例子:
const typeDefs = `
type Query {
events: [Event]
}
type Event {
type: String
payload: Payload
}
union Payload = Text | Joined
type Text {
test_string: String
}
type Joined {
received_events: String
invited_by: String
}
`;
// Since your type names and the specified types are different, we
// need to map them (resolveType needs to return the exact name)
const typesMap = {
text: 'Text',
joined: 'Joined'
}
const resolvers = {
Query: {
events: (root, args, context) => {
return [
{ type: 'text', payload: { test_string: 'Foo' } }
];
},
},
// We can use the resolver for the payload field to inject the type
// from the parent object into the payload object
Event: {
payload: (obj) => Object.assign({ type: obj.type }, obj.payload)
},
// The type can then be referenced inside resolveType
Payload: {
__resolveType: (obj) => typesMap[obj.type]
}
};