Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { MongoError } from 'mongodb';
- import { Model } from 'mongoose';
- import {
- HttpException,
- HttpStatus,
- Injectable,
- } from '@nestjs/common';
- import { InjectModel } from '@nestjs/mongoose';
- import {
- collectionName,
- TicketDepartments,
- TicketDepartmentsDocument,
- } from '../schemas/ticket-departments.schema';
- import { CreateTicketDepartmentDto } from '../dto/create-ticket-department.dto';
- import { UpdateTicketDepartmentDto } from '../dto/update-ticket-department.dto';
- @Injectable()
- class TicketDepartmentsRepository {
- constructor(
- @InjectModel(collectionName)
- private ticketDepartmentModel: Model<TicketDepartmentsDocument>,
- ) {}
- async insert(
- createTicketDepartmentDto: CreateTicketDepartmentDto,
- ): Promise<{ _id: string }> {
- const { members, name, title } = createTicketDepartmentDto;
- const ticketDepartment = await new this.ticketDepartmentModel(
- {
- members,
- name,
- title,
- },
- )
- .save()
- .catch(insertErrorCatcher);
- return {
- _id: ticketDepartment.id,
- };
- }
- async findAll(): Promise<{
- ticketDepartments: TicketDepartments[];
- }> {
- return {
- ticketDepartments: await this.ticketDepartmentModel
- .find()
- .exec(),
- };
- }
- async findById(_id: string): Promise<{
- ticketDepartment: TicketDepartments;
- }> {
- const ticketDepartment = await this.ticketDepartmentModel
- .findById(_id)
- .exec();
- documentExistanceChecker(ticketDepartment);
- return {
- ticketDepartment,
- };
- }
- async findByIdAndUpdate(
- _id: string,
- updateTicketDepartmentDto: UpdateTicketDepartmentDto,
- ): Promise<{
- ticketDepartment: TicketDepartments;
- }> {
- const ticketDepartment = await this.ticketDepartmentModel
- .findByIdAndUpdate(_id, { ...updateTicketDepartmentDto })
- .exec();
- documentExistanceChecker(ticketDepartment);
- return {
- ticketDepartment,
- };
- }
- }
- function documentExistanceChecker(document: any) {
- if (!document) {
- throw new HttpException(
- {
- status: HttpStatus.NOT_FOUND,
- error: 'Ticket department not found',
- },
- HttpStatus.NOT_FOUND,
- );
- }
- }
- function insertErrorCatcher(error: MongoError) {
- if (error.code == 11000) {
- throw new HttpException(
- {
- status: HttpStatus.CONFLICT,
- error: 'Inserted Ticket department confilicts with an existing Ticket department',
- },
- HttpStatus.CONFLICT,
- );
- }
- }
- export { TicketDepartmentsRepository };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement