![](/img/trans.png)
[英]TypeScript Class Implements Interface with Union Type Field results in Error (2322)
[英]Unable to return an interface or a union type from a field in the schema
我正在閱讀graphQL
文檔,在使用內聯片段和接口時發現了一個問題
他們在文檔中提到我們也可以在模式中返回接口或聯合類型,但 GraphiQL 返回以下錯誤。
“抽象類型“用戶”必須在運行時為字段“Query.user”解析為 Object 類型。“用戶”類型應提供“resolveType”function,或者每個可能的類型應提供“isTypeOf”function。”
索引.js
import express from "express";
import { graphqlHTTP } from "express-graphql";
import { buildSchema } from "graphql";
const UserStatuses = Object.freeze({
"registered": "REGISTERED",
"active": "ACTIVE",
"inactive": "INACTIVE"
});
const users = [
{
"id": 120,
"first_name": "Admin",
"last_name": "Kumar",
"email": "admin@yopmail.com",
"dob": "1980-01-01",
"age": 42,
"is_admin": true,
"status": UserStatuses['active']
},
{
"id": 121,
"first_name": "Sachin",
"last_name": "Kumar",
"email": "sachin@yopmail.com",
"dob": "1994-01-01",
"age": 28,
"status": UserStatuses['active'],
"tasks": []
},
{
"id": 122,
"first_name": "Sumit",
"last_name": "Kumar",
"email": "sumit@yopmail.com",
"dob": "1992-01-01",
"age": 30,
"status": UserStatuses['active'],
"tasks": []
},
{
"id": 123,
"first_name": "Akash",
"last_name": "Kumar",
"email": "akash@yopmail.com",
"dob": "1993-01-01",
"age": 29,
"status": UserStatuses['inactive'],
"tasks": []
},
{
"id": 124,
"first_name": "Ravi",
"last_name": "Kumar",
"email": "ravi@yopmail.com",
"dob": "1991-01-01",
"age": 31,
"status": UserStatuses['registered'],
"tasks": []
}
];
var schema = buildSchema(`
type Query {
user(id: Int): User
}
interface User {
id: ID!
first_name: String!
last_name: String!
email: String!
}
enum UserStatus {
REGISTERED
ACTIVE
INACTIVE
}
type AppUser implements User {
id: ID!
first_name: String!
last_name: String!
email: String!
age: Int!
status: UserStatus!
}
type AdminUser implements User {
id: ID!
first_name: String!
last_name: String!
email: String!
is_admin: Boolean
status: UserStatus!
}
`);
var root = {
user: function ({id}) {
let user = users.find(u => u.id == id);
return user;
},
}
var app = express();
// for testing purposes.
app.get('/', (req, res) => {
return res.send("Hello World!");
});
app.use('/graphql', graphqlHTTP({
schema,
rootValue: root,
pretty: true,
graphiql: true
}))
app.listen(4000, () => console.log('Graphql Server is browse to http://localhost:4000/graphql'));
我想在 GraphiQL 上執行的查詢
query general{
user(id: 120) {
id
first_name
__typename
}
}
您應該能夠向您的用戶 object 添加一個__resolveType
字段來消除歧義。
var root = {
user: function ({id}) {
let user = users.find(u => u.id === id);
user['__resolveType'] = user.is_admin ? 'AdminUser' : 'AppUser';
return user;
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.