feat: add pagination, sorting and filtering
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import { PaginationQueryDTO } from '@/common/dtos/pagination-query.dto';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
} from 'class-validator';
|
||||
import { AccessType } from '../enums/access-types.enum';
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { TestSortField } from '../enums/test-sort-field.enum';
|
||||
|
||||
export class FindTestsDTO extends PartialType(PaginationQueryDTO) {
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
id?: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
title?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
price?: string;
|
||||
|
||||
@IsEnum(AccessType)
|
||||
@IsOptional()
|
||||
accessType?: AccessType;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
isActive?: boolean;
|
||||
|
||||
@IsEnum(TestSortField)
|
||||
@IsOptional()
|
||||
sortBy?: TestSortField;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export enum TestSortField {
|
||||
ID = 'id',
|
||||
TITLE = 'title',
|
||||
DESCRIPTION = 'description',
|
||||
ACCESS_TYPE = 'accessType',
|
||||
PRICE = 'price',
|
||||
IS_ACTIVE = 'isActive',
|
||||
CREATED_AT = 'createdAt',
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { FindOptionsWhere, ILike } from 'typeorm';
|
||||
import { FindTestsDTO } from '../dtos/find-tests.dto';
|
||||
|
||||
export const filterTests = (query: FindTestsDTO) => {
|
||||
const where: FindOptionsWhere<any> = {};
|
||||
|
||||
if (query.id) {
|
||||
where.id = query.id;
|
||||
}
|
||||
|
||||
if (query.title) {
|
||||
where.title = ILike(`%${query.title}%`);
|
||||
}
|
||||
|
||||
if (query.description) {
|
||||
where.description = ILike(`%${query.description}%`);
|
||||
}
|
||||
|
||||
if (query.accessType !== undefined) {
|
||||
where.accessType = query.accessType;
|
||||
}
|
||||
|
||||
if (query.price !== undefined) {
|
||||
where.price = query.price;
|
||||
}
|
||||
|
||||
if (query.isActive !== undefined) {
|
||||
where.isActive = query.isActive;
|
||||
}
|
||||
|
||||
return where;
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { CreateTestDTO } from '../dtos/create-test.dto';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Test } from '../entities/test.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { I18nService } from 'nestjs-i18n';
|
||||
import { AppException } from '@/common/exceptions/app.exception';
|
||||
import { AppResponse } from '@/common/responses';
|
||||
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
||||
import { UpdateTestDTO } from '../dtos/update-test.dto';
|
||||
import { AccessType } from '../enums/access-types.enum';
|
||||
|
||||
@Injectable()
|
||||
export class TestsCommandProvider {
|
||||
constructor(
|
||||
/**
|
||||
* Inject Tests Repository
|
||||
*/
|
||||
@InjectRepository(Test)
|
||||
private readonly testRepository: Repository<Test>,
|
||||
|
||||
/**
|
||||
* Inject I18n Service
|
||||
*/
|
||||
private readonly i18nService: I18nService,
|
||||
) {}
|
||||
|
||||
public async createOne(createTestDto: CreateTestDTO) {
|
||||
const titleExists = await this.testRepository.findOne({
|
||||
where: {
|
||||
title: createTestDto.title,
|
||||
},
|
||||
});
|
||||
|
||||
if (titleExists) {
|
||||
throw new AppException('validation.duplicateField', HttpStatus.CONFLICT, {
|
||||
field: '$t(tests.fields.title)',
|
||||
});
|
||||
}
|
||||
|
||||
const newTest = this.testRepository.create(createTestDto);
|
||||
|
||||
try {
|
||||
await this.testRepository.save(newTest);
|
||||
return new AppResponse(
|
||||
newTest,
|
||||
this.i18nService.translate('tests.messages.createSuccess'),
|
||||
);
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
}
|
||||
|
||||
public async updateOne(id: number, updateTestDto: UpdateTestDTO) {
|
||||
const test = await this.testRepository.findOneBy({ id });
|
||||
|
||||
if (!test) {
|
||||
throw new NotFoundException('tests.errors.testNotFound');
|
||||
}
|
||||
|
||||
const accessType = updateTestDto.accessType ?? test.accessType;
|
||||
const price = updateTestDto.price ?? test.price;
|
||||
|
||||
if (
|
||||
(accessType === AccessType.PAID && !price) ||
|
||||
(accessType !== AccessType.PAID && price)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
this.i18nService.translate('tests.errors.priceAccessConstraint'),
|
||||
);
|
||||
}
|
||||
|
||||
Object.assign(test, updateTestDto);
|
||||
|
||||
try {
|
||||
return await this.testRepository.save(test);
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
}
|
||||
|
||||
public async deleteOne(id: number) {
|
||||
let test: Test | null = null;
|
||||
|
||||
try {
|
||||
test = await this.testRepository.findOneBy({ id });
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
|
||||
if (!test) throw new NotFoundException('tests.errors.testNotFound');
|
||||
|
||||
try {
|
||||
await this.testRepository.delete(test.id);
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { PaginatedResponse } from '@/common/responses';
|
||||
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
||||
import { FindTestsDTO } from '../dtos/find-tests.dto';
|
||||
import { filterTests } from '../helpers/filter-tests.helper';
|
||||
import Utils from '@/common/utils';
|
||||
import { Test } from '../entities/test.entity';
|
||||
|
||||
@Injectable()
|
||||
export class TestsQueryProvider {
|
||||
constructor(
|
||||
/**
|
||||
* Inject Tests Repository
|
||||
*/
|
||||
@InjectRepository(Test)
|
||||
private readonly testRepository: Repository<Test>,
|
||||
) {}
|
||||
|
||||
public async findAllForAdmin(query: FindTestsDTO) {
|
||||
const filterOptions = filterTests(query);
|
||||
const { page, take, limit, skip } =
|
||||
Utils.PaginationUtils.getPaginationOptions(query);
|
||||
|
||||
try {
|
||||
const [tests, total] = await this.testRepository.findAndCount({
|
||||
where: filterOptions,
|
||||
skip,
|
||||
take,
|
||||
order: query.sortBy
|
||||
? {
|
||||
[query.sortBy]: query.order ?? 'ASC',
|
||||
}
|
||||
: { createdAt: 'DESC' },
|
||||
});
|
||||
|
||||
return new PaginatedResponse(tests, {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
}
|
||||
|
||||
public async findAllForUser() {
|
||||
try {
|
||||
return await this.testRepository.find({
|
||||
where: { isActive: true },
|
||||
select: {
|
||||
id: true,
|
||||
accessType: true,
|
||||
description: true,
|
||||
price: true,
|
||||
title: true,
|
||||
},
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
}
|
||||
|
||||
public async findOneForAdmin(id: number) {
|
||||
try {
|
||||
return await this.testRepository.findOneBy({ id });
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
}
|
||||
|
||||
public async findOneForUser(id: number) {
|
||||
let test: Test | null;
|
||||
|
||||
try {
|
||||
test = await this.testRepository.findOne({
|
||||
where: { id, isActive: true },
|
||||
select: {
|
||||
id: true,
|
||||
accessType: true,
|
||||
description: true,
|
||||
price: true,
|
||||
title: true,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
|
||||
if (!test) {
|
||||
throw new NotFoundException('tests.errors.testNotFound');
|
||||
}
|
||||
|
||||
return test;
|
||||
}
|
||||
}
|
||||
@@ -1,163 +1,49 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
RequestTimeoutException,
|
||||
} from '@nestjs/common';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Test } from '../entities/test.entity';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CreateTestDTO } from '../dtos/create-test.dto';
|
||||
import { AppException } from '@/common/exceptions/app.exception';
|
||||
import { AppResponse } from '@/common/responses';
|
||||
import { I18nService } from 'nestjs-i18n';
|
||||
import { UpdateTestDTO } from '../dtos/update-test.dto';
|
||||
import { AccessType } from '../enums/access-types.enum';
|
||||
import { FindTestsDTO } from '../dtos/find-tests.dto';
|
||||
import { TestsQueryProvider } from './tests-query.provider';
|
||||
import { TestsCommandProvider } from './tests-command.provider';
|
||||
|
||||
@Injectable()
|
||||
export class TestsService {
|
||||
constructor(
|
||||
/**
|
||||
* Inject Tests Repository
|
||||
* Inject Tests Query Provider
|
||||
*/
|
||||
@InjectRepository(Test)
|
||||
private readonly testRepository: Repository<Test>,
|
||||
private readonly testsQueryProvider: TestsQueryProvider,
|
||||
|
||||
/**
|
||||
* Inject I18n Service
|
||||
* Inject Tests Command Provider
|
||||
*/
|
||||
private readonly i18nService: I18nService,
|
||||
private readonly testsCommandProvider: TestsCommandProvider,
|
||||
) {}
|
||||
|
||||
public async createOne(createTestDto: CreateTestDTO) {
|
||||
const titleExists = await this.testRepository.findOne({
|
||||
where: {
|
||||
title: createTestDto.title,
|
||||
},
|
||||
});
|
||||
|
||||
if (titleExists) {
|
||||
throw new AppException('validation.duplicateField', HttpStatus.CONFLICT, {
|
||||
field: '$t(tests.fields.title)',
|
||||
});
|
||||
}
|
||||
|
||||
const newTest = this.testRepository.create(createTestDto);
|
||||
|
||||
try {
|
||||
await this.testRepository.save(newTest);
|
||||
return new AppResponse(
|
||||
newTest,
|
||||
this.i18nService.translate('tests.messages.createSuccess'),
|
||||
);
|
||||
} catch (err) {
|
||||
throw new RequestTimeoutException('common.errors.requestTimeout', {
|
||||
cause: err,
|
||||
description: 'Error connecting to the database',
|
||||
});
|
||||
}
|
||||
return await this.testsCommandProvider.createOne(createTestDto);
|
||||
}
|
||||
|
||||
public async adminGetAll() {
|
||||
try {
|
||||
return await this.testRepository.find({ order: { createdAt: 'DESC' } });
|
||||
} catch (err) {
|
||||
throw new RequestTimeoutException('common.errors.requestTimeout', {
|
||||
cause: err,
|
||||
description: 'Error connecting to the database',
|
||||
});
|
||||
}
|
||||
public async adminGetAll(query: FindTestsDTO) {
|
||||
return await this.testsQueryProvider.findAllForAdmin(query);
|
||||
}
|
||||
|
||||
public async userGetAll() {
|
||||
try {
|
||||
return await this.testRepository.find({
|
||||
where: { isActive: true },
|
||||
select: {
|
||||
id: true,
|
||||
accessType: true,
|
||||
description: true,
|
||||
price: true,
|
||||
title: true,
|
||||
},
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
} catch (err) {
|
||||
throw new RequestTimeoutException('common.errors.requestTimeout', {
|
||||
cause: err,
|
||||
description: 'Error connecting to the database',
|
||||
});
|
||||
}
|
||||
return await this.testsQueryProvider.findAllForUser();
|
||||
}
|
||||
|
||||
public async adminGetOne(id: number) {
|
||||
try {
|
||||
return await this.testRepository.findOneBy({ id });
|
||||
} catch (err) {
|
||||
throw new RequestTimeoutException('common.errors.requestTimeout', {
|
||||
cause: err,
|
||||
description: 'Error connecting to the database',
|
||||
});
|
||||
}
|
||||
return await this.testsQueryProvider.findOneForAdmin(id);
|
||||
}
|
||||
|
||||
public async userGetOne(id: number) {
|
||||
let test: Test | null;
|
||||
|
||||
try {
|
||||
test = await this.testRepository.findOne({
|
||||
where: { id, isActive: true },
|
||||
select: {
|
||||
id: true,
|
||||
accessType: true,
|
||||
description: true,
|
||||
price: true,
|
||||
title: true,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
throw new RequestTimeoutException('common.errors.requestTimeout', {
|
||||
cause: err,
|
||||
description: 'Error connecting to the database',
|
||||
});
|
||||
}
|
||||
|
||||
if (!test) {
|
||||
throw new NotFoundException('tests.errors.testNotFound');
|
||||
}
|
||||
|
||||
return test;
|
||||
return await this.testsQueryProvider.findOneForUser(id);
|
||||
}
|
||||
|
||||
public async updateOne(id: number, updateTestDto: UpdateTestDTO) {
|
||||
const test = await this.testRepository.findOneBy({ id });
|
||||
return await this.testsCommandProvider.updateOne(id, updateTestDto);
|
||||
}
|
||||
|
||||
if (!test) {
|
||||
throw new NotFoundException('tests.errors.testNotFound');
|
||||
}
|
||||
|
||||
const accessType = updateTestDto.accessType ?? test.accessType;
|
||||
const price = updateTestDto.price ?? test.price;
|
||||
|
||||
if (
|
||||
(accessType === AccessType.PAID && !price) ||
|
||||
(accessType !== AccessType.PAID && price)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
this.i18nService.translate('tests.errors.priceAccessConstraint'),
|
||||
);
|
||||
}
|
||||
|
||||
Object.assign(test, updateTestDto);
|
||||
|
||||
try {
|
||||
return await this.testRepository.save(test);
|
||||
} catch (err) {
|
||||
throw new RequestTimeoutException('common.errors.requestTimeout', {
|
||||
cause: err,
|
||||
description: 'Error connecting to the database',
|
||||
});
|
||||
}
|
||||
public async deleteOne(id: number) {
|
||||
return await this.testsCommandProvider.deleteOne(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,13 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Test } from './entities/test.entity';
|
||||
import { TestsService } from './providers/tests.service';
|
||||
import { TestsController } from './tests.controller';
|
||||
import { TestsQueryProvider } from './providers/tests-query.provider';
|
||||
import { TestsCommandProvider } from './providers/tests-command.provider';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Test])],
|
||||
controllers: [TestsController],
|
||||
providers: [TestsService],
|
||||
providers: [TestsService, TestsQueryProvider, TestsCommandProvider],
|
||||
exports: [TestsService],
|
||||
})
|
||||
export class TestsModule {}
|
||||
|
||||
Reference in New Issue
Block a user