У меня есть следующая схема мангуста:
const MessageSchema = new Schema({
author: {
account:{
type:String,
enum:['employee','admin'],
},
id: String,
}
//other fields
})
Затем в моем файле graphql-schemas у меня есть следующие типы схем:
const MessageType = new GraphQLObjectType({
name: 'Message',
fields: () => ({
account: {
type: AuthorType,
//resolve method
},
id: {type: GraphQLString},
})
})
const AuthorType= new GraphQLObjectType({
name: 'Author',
fields: () => ({
account: {
type://This will either be AdminType or EmployeeType depending on the value of account in db (employee or admin),
//resolve method code goes here
}
})
})
Как указано в комментариях к AuthorType, мне нужно, чтобы поле account разрешалось в Admin или Employee в зависимости от значения поля account в базе данных.
Как на лету условно определить тип поля в схеме?


Вместо того, чтобы определять тип на лету, я реструктурировал свой код, как показано ниже:
const MessageType = new GraphQLObjectType({
name: 'Message',
fields: () => ({
id:{type:GraphQLString},
author: {
type: AuthorType,
async resolve(parent, args) {
if (parent.author.account === 'guard') {
return await queries.findEmployeeByEmployeeId(parent.author.id).then(guard => {
return {
username: `${guard.first_name} ${guard.last_name}`,
profile_picture: guard.profile_picture
}
})
} else if (parent.author.account === 'admin') {
return {
username: 'Administrator',
profile_picture: 'default.jpg'
}
}
}
},
//other fields
})
})
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
username: {type: GraphQLString},
profile_picture: {type: GraphQLString},
})
})
Поскольку все, что мне нужно от AuthorType, - это имя пользователя и изображение профиля автора, эти поля есть как у сотрудника, так и у администратора, которые я передаю в AuthorType.
В MessageType я применяю логику для определения типа учетной записи в методе resolveauthor, а затем конструирую пользовательский объект из логики, чтобы соответствовать AuthorType.