Your IP : 216.73.216.220


Current Path : /home/deltalab/PMS/partner-manager-backend/graphql/schema/
Upload File :
Current File : //home/deltalab/PMS/partner-manager-backend/graphql/schema/category.schema.js

const auth = require('../../services/auth.js');

const { categoryTC } = require('../types/category.type');
const { attributeTC } = require('../types/category.type');

const { categoryModel } = require('../../models/mongoose/category');

// RESOLVERS =========================================
/**
 * Listing all root categories
 */
categoryTC.addResolver({
  kind: 'query',
  name: 'categoryRoots',
  type: [categoryTC],
  resolve: async () => {
    const categories = await categoryModel.find({ isRoot: true });
    return categories;
  },
});

categoryTC.addResolver({
  kind: 'query',
  name: 'categoryByGoogleId',
  type: categoryTC,
  args: {
    googleId: 'String!',
  },
  resolve: async ({ args }) => {
    const category = await categoryModel.findOne({ googleId: args.googleId });
    return category;
  },
});

/**
 * Lising all attributes of a given category
 */
categoryTC.addResolver({
  kind: 'query',
  name: 'categoryAttributes',
  type: [attributeTC],
  args: {
    categoryId: 'MongoID!',
  },
  resolve: async ({ args }) => {
    let attributes = [];
    let category = await categoryModel.findOne({ _id: args.categoryId });
    attributes = category.attributes.concat(attributes);
    while (category.parentId) {
      category = await categoryModel.findOne({ _id: category.parentId });
      attributes = category.attributes.concat(attributes);
    }
    return attributes;
  },
});

// RELATIONS =========================================
categoryTC.addRelation(
  'parent',
  {
    resolver: () => categoryTC.mongooseResolvers.findById(),
    prepareArgs: {
      _id: (source) => source.parentId,
    },
    projection: { parentId: true },
  },
);

categoryTC.addRelation(
  'children',
  {
    resolver: () => categoryTC.mongooseResolvers.findByIds(),
    prepareArgs: {
      _ids: (source) => source.childrenId,
    },
    projection: { childrenId: true },
  },
);

// CUSTOM RESOLVERS ==================================

// QUERIES ===========================================
const categoryQuery = {
  ...auth.authenticationRequired({
    categoryById: categoryTC.mongooseResolvers.findById(),
    categoryOne: categoryTC.mongooseResolvers.findOne(),
    categoryMany: categoryTC.mongooseResolvers.findMany(),
    categoryCount: categoryTC.mongooseResolvers.count(),
    categoryRoots: categoryTC.getResolver('categoryRoots'),
    categoryByGoogleId: categoryTC.getResolver('categoryByGoogleId'),
    categoryAttributes: categoryTC.getResolver('categoryAttributes'),
  }),
};

// MUTATIONS =========================================
const categoryMutation = {
  ...auth.authenticationRequired({
  }),
};

// EXPORTS ===========================================
module.exports = {
  categoryQuery,
  categoryMutation,
};