mickhansen / graphql-sequelize

GraphQL & Relay for MySQL & Postgres via Sequelize
MIT License
1.9k stars 172 forks source link

Handling 1-to-1 relationships (hasOne) in resolver #582

Closed moseleyi closed 6 years ago

moseleyi commented 6 years ago

We finally got to the bottom why I had so many problems with values.map.

In our database we have few 1-to-1 relationships between models. From coding perspective it may not make sense but from database perspective it does a lot. For example our users table is very small, it contains only small portion of data that is accessed all the time, and then we have separate table that keeps all long-text fields, which is not accessed as often. Therefore we have 1-to-1 between User and UserDetail.

If in Sequelize I specify this relationship as hasOne this line of code fails:

let edges = values.map(function (value, idx) {
    return resolveEdge(value, idx, cursor, args, source);
});

it fails because values is required to be a collection of objects, however with hasOne you are getting one object. We have solved it by refactoring the resolver for 1-to-1 relationships but I'm sure it could be handled in the core code.

mickhansen commented 6 years ago

Any reason you couldn't just dump connections for 1-to-1 relations? You wouldn't really need pagination or anything like that for those cases.

When you have simple associations you can use resolver(Association) rather than create a full connection.

Other than that, it should be a simple core fix, coercing an array.

moseleyi commented 6 years ago

No reason, I did what you suggested and everything works great now. It would be good to put this into documentation. I'm fairly new to Sequelize and GraphQL and those things just don't pop to my head : )

mickhansen commented 6 years ago

Documentation PR welcome @moseleyi, it's sometimes easier when docs are adjusted by people who have have experienced real issues :)

moseleyi commented 6 years ago

I agree, thanks I will write something up when I get a chance