0

I have 2 Models, User and Post. I want to be able to get User information when querying a post, and be able to get all of a User's posts when querying a user.

they have an association as follows:

User.hasMany(Post, {
    foreignKey: 'user',
    as: 'posts'
});
Post.belongsTo(User, {
    foreignKey: 'id',
    sourceKey: 'user',
    as: 'userObject'
})

Post.addScope('defaultScope', {
    include: [{ model: User, as: 'userObject' }],
}, { override: true })

User.addScope('defaultScope', {
    include: [{ model: Post, as: 'posts' }],
}, { override: true })

Here are my Models

User.js

module.exports.userType = new GQL.GraphQLObjectType({
    name: 'User',
    fields: () => {
        const { postType } = require('../Post/Post');
        return {
            id: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'user unique id'
            },
            ci_username: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                unique: true,
                description: 'case INSENSITIVE username of the user'
            },
            username: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'case SENSITIVE username of the user'
            },
            password: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'password for the user'
            },
            first_name: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'first name of user'
            },
            last_name: {
                type: GQL.GraphQLString,
                description: 'last name of user (optional)'
            },
            profile_picture: {
                type: GQL.GraphQLString,
                description: 'profile picture for the user'
            },
            posts: {
                type: GQL.GraphQLList(postType),
                description: 'list of users posts'
            }
        }
    },
})

/** define User model for the database */
module.exports.User = db.define('user', {
    id: {
        type: Sequelize.UUID,
        primaryKey: true, 
        unique: true,
    },
    ci_username: {
        type: Sequelize.STRING,
        unique: true,
    },
    username: Sequelize.STRING,
    password: Sequelize.STRING,
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING,
    profile_picture: Sequelize.STRING,
}, {
    // Tells sequelize not to query the "CreatedAt" or "UpdatedAt" Columns
    timestamps: false
})

Post.js

module.exports.postType = new GQL.GraphQLObjectType({
    name: 'Post',
    fields: () => {
        const { userType } = require('../User/User');
        return {
            id: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'post unique id'
            },
            name: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'name of the post'
            },
            user: {
                type: userType,
                description: 'user object of who created the post'
            },
            created_at: {
                type: new GQL.GraphQLNonNull(GQL.GraphQLString),
                description: 'the datetime the post was created',
            }
        }
    },
})

/** define User model for the database */
module.exports.Post = db.define('post', {
    id: {
        type: DataTypes.UUID,
        primaryKey: true, 
        unique: true,
    },
    name: DataTypes.STRING,
    user: {
        type: DataTypes.STRING,
        references: {
            model: 'users',
            key: 'id'
        }
    },
    created_at: {
        type: DataTypes.TIME,
        defaultValue: DataTypes.NOW
    }
}, {
    // Tells sequelize not to query the "CreatedAt" or "UpdatedAt" Columns
    timestamps: false
})

Here are my Queries:

allUsers.js

const allUsers = {
    type: new GQL.GraphQLList(userType),
    args: {
        username: {
            description: 'username of the user',
            type: GQL.GraphQLString,
        },
        // An arg with the key limit will automatically be converted to a limit on the target
        limit: {
            type: GQL.GraphQLInt,
            default: 10
        },
        // An arg with the key order will automatically be converted to a order on the target
        order: {
            type: GQL.GraphQLString
        }
    },
    // use graphql-sequelize resolver with the User model from database
    resolve: resolver(User)
}

allPosts.js

const allPosts = {
    type: new GQL.GraphQLList(postType),
    args: {
        username: {
            description: 'username of the user',
            type: GQL.GraphQLString,
        },
        // An arg with the key limit will automatically be converted to a limit on the target
        limit: {
            type: GQL.GraphQLInt,
            default: 10
        },
        // An arg with the key order will automatically be converted to a order on the target
        order: {
            type: GQL.GraphQLString
        }
    },
    // use graphql-sequelize resolver with the Post model from database
    resolve: resolver(Post)
}

I'm currently getting a Maximum call stack size exceeded. I assume because the resolver in the queries are recursively getting details on posts and users infinitely.

Does anyone know of any way to put a depth limitation on the resolver? Or is it just not possible to have a recursive query like this?

Jesse Sainz
  • 131
  • 1
  • 12

1 Answers1

1

You would have to remove the default scope from the included model as shown here like this:

Post.addScope('defaultScope', {
    include: [{ model: User.scope(null), as: 'userObject' }],
}, { override: true })

User.addScope('defaultScope', {
    include: [{ model: Post.scope(null), as: 'posts' }],
}, { override: true })

To support additional depth, you'd need to implement resolvers for the fields in question, for example:

function resolve (user) {
  if (user.posts) {
    return user.posts
  }
  return user.getPosts()
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thanks, that seemed to work for the allUsers query, but for some reason, the JOIN for the allPosts query return null for the user attribute. Although when I run the same query in the SQL console it works fine. Any idea what the issue might be? – Jesse Sainz Jan 24 '20 at 04:17
  • The query ends up being `SELECT "post"."id", "post"."name", "post"."user", "post"."created_at", "userObject"."id" AS "userObject.id", "userObject"."ci_username" AS "userObject.ci_username", "userObject"."username" AS "userObject.username", "userObject"."password" AS "userObject.password", "userObject"."first_name" AS "userObject.first_name", "userObject"."last_name" AS "userObject.last_name", "userObject"."profile_picture" AS "userObject.profile_picture" FROM "posts" AS "post" LEFT OUTER JOIN "users" AS "userObject" ON "post"."user" = "userObject"."id" ORDER BY "post"."id" ASC;` – Jesse Sainz Jan 24 '20 at 04:18
  • You're aliasing the association as `userObject` but there is no field with that name on your type. – Daniel Rearden Jan 24 '20 at 04:19
  • As soon as I make the alias and the field match I get this error though: `Naming collision between attribute 'userObject' and association 'userObject' on model post. To remedy this, change either foreignKey or as in your association definition` – Jesse Sainz Jan 24 '20 at 04:25
  • 1
    Change the `as` in the association definition as the error suggestions – Daniel Rearden Jan 24 '20 at 04:28
  • Ah I see. Got it. Thank you so much for the help! – Jesse Sainz Jan 24 '20 at 04:42