我想知道如何传递“子”类型的参数。 有了请求,我只希望收到来自用户ID 1的ID为1的消息。
当前我有此请求:
{user(id:1){
email,
username,
messages(id:1){
text,
id
}
}}
我在架构中修改了用户类型,然后更改了
messages: [Message]
作者
messages(id: Int): [Message]
但是我总是收到来自用户的所有消息,而不是具有特定ID的消息。
schema.js
import { gql } from 'apollo-server';
export const typeDefs = gql`
# declare custom scalars
scalar Date
##########
## TYPE ##
##########
# a group
type Group {
id: Int!
name: String
users: [User]!
messages: [Message]
}
# a user
type User {
id: Int! # unique id for the user
email: String!
username: String
messages(id: Int): [Message]
groups: [Group]
friends: [User]
}
# a message sent from a user to a group
type Message {
id: Int!
to: Group!
from: User!
text: String!
createdAt: Date!
}
###########
## QUERY ##
###########
# query for types
type Query {
user(email: String, id: Int): User
messages(groupId: Int, userId: Int): [Message]
}
schema {
query: Query
}
`;
export default typeDefs;
resolvers.js
import GraphQLDate from 'graphql-date';
import { Group, Message, User } from './connectors';
export const resolvers = {
Date: GraphQLDate,
Query: {
group(_, args) {
return Group.find({ where: args });
},
messages(_, args) {
return Message.findAll({
where: args,
order: [['createdAt', 'DESC']],
});
},
user(_, args) {
return User.findOne({ where: args });
},
},
Group: {
users(group) {
return group.getUsers();
},
messages(group) {
return Message.findAll({
where: { groupId: group.id },
order: [['createdAt', 'DESC']],
});
},
},
Message: {
to(message) {
return message.getGroup();
},
from(message) {
return message.getUser();
},
},
User: {
messages(user) {
return Message.findAll({
where: { userId: user.id },
order: [['createdAt', 'DESC']],
});
},
groups(user) {
return user.getGroups();
},
friends(user) {
return user.getFriends();
},
},
};
export default resolvers;
答案 0 :(得分:1)
您必须更新User.messages
解析器。这样:
User: {
messages(user, { id }) {
return Message.findAll({
where: { userId: user.id, id },
order: [['createdAt', 'DESC']],
});
},
groups(user) {
return user.getGroups();
},
friends(user) {
return user.getFriends();
},
},
如果您想将id
参数设置为可选参数,则可能会有所帮助:
messages(user, { id }) {
const where = { userId: user.id }
if (id) {
where.id = id
}
return Message.findAll({
where,
order: [['createdAt', 'DESC']],
});
},