I'm setting up resolvers for a GraphQL API right now and running into some problems/questions regarding the findAll() function from sequelize.
I have these 2 resolvers:
User: async (parent, { id }, { models }) => {
return await models.User.findAll({
where: {
ID_User: id
}
});
}
UserPK: async (parent, { id }, { models }) => {
return await models.User.findByPk(id);
}
Models:
type Query {
UserPK(id: ID): User
User(id: ID): User
}
type User {
ID_User: ID,
Username: String,
}
If I now run these queries
{
UserPK(id: 1) {
ID_User
Username
}
User(id: 1) {
ID_User
Username
}
}
Only the UserPK returns (correct) data, the User query returns null for every field which confuses me because the queries sequelize executes are exactly the same.
Executing (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';
Executing (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';
I'm using apollo server btw if that makes any difference.
The difference between findByPk and findAll is that findByPk returns already a single element whereas findAll returns and array. You don't seem to take that into account. After that the resolvers for User receive an array where they cannot read properties from.
return (await models.User.findAll({
where: {
ID_User: id
}
}))[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With