File

lib/shared/modules/category/category.service.ts

Description

Service for working with tree-categories.

Index

Methods

Constructor

constructor(catRep: TreeRepository<CategoryEntity>, logger: Logger)
Parameters :
Name Type Optional
catRep TreeRepository<CategoryEntity> No
logger Logger No

Methods

Async getDescendantsByCodeOfRoot
getDescendantsByCodeOfRoot(code: string, depth?: number)

Get descendants of a category by its code.

Parameters :
Name Type Optional Description
code string No

The code of the root category.

depth number Yes

The maximum depth for the search (optional).

Returns : unknown

A promise that resolves to the tree of descendants of the category.

Private sort
sort(cat: CategoryEntity)

Sorts the children of a category by priority.

Parameters :
Name Type Optional Description
cat CategoryEntity No
  • The category entity whose children need to be sorted.
Returns : void
import { Inject, Injectable, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { TreeRepository } from "typeorm";
import { CategoryEntity } from "./entity/category.entity";
import { LOGGER } from "../log/log.constants";
import { CATEGORY_RELATIONS } from "./category.constants";
import { ObjectUtils } from "../../utils/object.utils";

/**
 * Service for working with tree-categories.
 */
@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly catRep: TreeRepository<CategoryEntity>,
    @Inject(LOGGER) private readonly logger: Logger,
  ) {}

  /**
   * Get descendants of a category by its code.
   * @param code The code of the root category.
   * @param depth The maximum depth for the search (optional).
   * @returns A promise that resolves to the tree of descendants of the category.
   */
  async getDescendantsByCodeOfRoot(code: string, depth?: number) {
    const cat = await this.catRep.findOne({
      where: { code },
      relations: CATEGORY_RELATIONS,
    });
    if (!cat) {
      return null;
    }
    const res = await this.catRep.findDescendantsTree(cat, {
      depth,
      relations: CATEGORY_RELATIONS,
    });
    if (!res.children?.length) {
      return res;
    }
    res.children.forEach((cat) => this.sort(cat));
    this.sort(res);
    return res;
  }

  /**
   * Sorts the children of a category by priority.
   * @param cat - The category entity whose children need to be sorted.
   */
  private sort(cat: CategoryEntity) {
    ObjectUtils.sort<CategoryEntity>(cat.children, "priority", false);
  }
}

results matching ""

    No results matching ""