mickhansen / graphql-sequelize

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

null belongsTo lookup results in empty sequelize instance #679

Closed mschipperheyn closed 4 years ago

mschipperheyn commented 4 years ago

I'm not sure why this occurs and whether this is expected behavior.

I have implemented resolver to load associations in combination with dataloader.

I have an object with the following association:

Account.belongsTo(models.Photo, {
    foreignKey: 'photoId',
    constraints: false,
    onDelete: 'cascade',
    as: 'photo',
});

The resolver type for Account looks like this:

photo: resolver(() => models.Account.associations.photo),

When photoId is null, I get an empty sequelize instance (no dataValues) instead of null, resulting in errors. I ended up resolving this overwriting the resolver, but I'm still trying to get it. Doesn't seem to happen on other associations without constraints: false

import { resolver as coreResolver } from 'graphql-sequelize';
import getDataloader from './sequelize/middleware/dataloader';

const createNullAfter = result => {
    if (!Array.isArray(result)) {
        if (
            !result ||
            Object.entries(
                result.get({
                    plain: true,
                }),
            ).length === 0
        )
            return null;
        return result;
    }
    return result;
};

export const resolver = (Model, options) =>
    coreResolver(Model, {
        after: createNullAfter,
        ...options,
    });
mickhansen commented 4 years ago

A null value should simply result in a null result. I'm not sure if the issue here is in graphql-sequelize, dataloader-sequelize (if you use that) or in sequelize itself.

mschipperheyn commented 4 years ago

I do use dataloader-sequelize. So, it's weird. I thought so. I'll try to do some logging and try to figure it out.

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.