victorteokw / graphql-joker

GraphQL Joker is the ultimate GraphQL scaffolding tool.
GNU General Public License v3.0
74 stars 9 forks source link

create additional api resource for array of objects and also deep nested #13

Closed victorteokw closed 6 years ago

victorteokw commented 6 years ago

customerCreditCard customerCreditCards createCustomerCreditCard updateCustomerCreditCard deleteCustomerCreditCard insertCustomerCreditCardAt moveCustomerCreditCardTo

victorteokw commented 6 years ago

Post a working resolver:

module.exports = {
  UserPostComment: {
    async commenter(root, _, ctx) {
      const { User } = ctx.models;
      return await User.findById(root.commenter);
    }
  },
  Query: {
    async user(root, { _id }, ctx) {
      const { User } = ctx.models;
      return await User.findById(_id);
    },
    async users(root, { _ }, ctx) {
      const { User } = ctx.models;
      return await User.find();
    },
    async userPost(root, { user, _id }, ctx) {
      const { User } = ctx.models;
      return (await User.findById(user).select('posts')).posts.id(_id);
    },
    async userPosts(root, { user }, ctx) {
      const { User } = ctx.models;
      return (await User.findById(user).select('posts')).posts;
    }
  },
  Mutation: {
    async createUser(root, { input }, ctx) {
      const { User } = ctx.models;
      return await User.create(input);
    },
    async updateUser(root, { _id, input }, ctx) {
      const { User } = ctx.models;
      return await User.findByIdAndUpdateByMerge(_id, input);
    },
    async deleteUser(root, { _id }, ctx) {
      const { User } = ctx.models;
      return await User.findByIdAndDelete(_id);
    },
    async createUserPost(root, { user, input }, ctx) {
      const { User } = ctx.models;
      const u = await User.findByIdAndUpdate(user, { $push: { posts: input }}, { new: true });
      return u.posts[u.posts.length - 1];
    },
    async deleteUserPost(root, { user, _id }, ctx) {
      const { User } = ctx.models;
      const u = await User.findByIdAndUpdate(user, { $pull: { posts: { _id }}}, { new: false });
      return u.posts.id(_id);
    },
  }
};
victorteokw commented 6 years ago

There are much more troubles when doing paging and filtering. This kind of design, should be avoid. So postpone this for now.

victorteokw commented 6 years ago

This will not be supported.

Here are the reasons:

Nested resources are hard to query, hard to save, and decreases performance. Nested resources lacks validation hooks, save hooks, remove hooks.

User should avoid this anti-pattern.