feat: add admin tests read and update endpoints

This commit is contained in:
2026-06-06 13:33:56 +03:30
parent 39e6c96113
commit 28c1a4831e
31 changed files with 330 additions and 101 deletions
@@ -0,0 +1,6 @@
import { Validate } from 'class-validator';
import { PriceAccessTypeConstraint } from '../validators/price-access-type-constraint.validator';
export const PriceAccessType = () => {
return Validate(PriceAccessTypeConstraint);
};
+6 -2
View File
@@ -9,6 +9,7 @@ import {
} from 'class-validator';
import { i18nValidationMessage as t } from 'nestjs-i18n';
import { AccessType } from '../enums/access-types.enum';
import { PriceAccessType } from '../decorators/price-access-type.decorator';
export class CreateTestDTO {
@IsString()
@@ -23,7 +24,7 @@ export class CreateTestDTO {
max: 255,
}),
})
title: string;
title!: string;
@IsString()
@IsNotEmpty({
@@ -31,7 +32,7 @@ export class CreateTestDTO {
field: '$t(tests.fields.description)',
}),
})
description: string;
description!: string;
@IsEnum(AccessType)
@IsOptional()
@@ -45,4 +46,7 @@ export class CreateTestDTO {
@IsBoolean()
@IsOptional()
isActive?: boolean;
@PriceAccessType()
private readonly _priceAccessValidation!: never;
}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateTestDTO } from './create-test.dto';
export class UpdateTestDTO extends PartialType(CreateTestDTO) {}
+16 -10
View File
@@ -1,4 +1,5 @@
import {
Check,
Column,
CreateDateColumn,
Entity,
@@ -12,9 +13,14 @@ import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { RuleSet } from '@/modules/scoring/entities/rule-set.entity';
@Entity()
@Check(`
("price" IS NULL AND "accessType" <> 'paid')
OR
("price" IS NOT NULL AND "accessType" = 'paid')
`)
export class Test {
@PrimaryGeneratedColumn()
id: number;
id!: number;
@Column({
type: 'varchar',
@@ -22,42 +28,42 @@ export class Test {
nullable: false,
unique: true,
})
title: string;
title!: string;
@Column({
type: 'text',
nullable: false,
})
description: string;
description!: string;
@Column({
type: 'enum',
enum: AccessType,
default: AccessType.LOGIN,
})
accessType: AccessType;
accessType!: AccessType;
@Column({
type: 'bigint',
nullable: true,
})
price: string;
price!: string;
@Column({
type: 'boolean',
default: false,
})
isActive: boolean;
isActive!: boolean;
@OneToMany(() => Question, (question) => question.test)
questions: Array<Question>;
questions!: Array<Question>;
@OneToOne(() => RuleSet, (ruleSet) => ruleSet.test)
ruleSet: RuleSet;
ruleSet!: RuleSet;
@OneToMany(() => ResultRange, (range) => range.test)
resultRanges: Array<ResultRange>;
resultRanges!: Array<ResultRange>;
@CreateDateColumn()
createdAt: Date;
createdAt!: Date;
}
@@ -0,0 +1,3 @@
GET http://localhost:3000/tests
GET http://localhost:3000/tests/4
@@ -1,6 +1,8 @@
import {
BadRequestException,
HttpStatus,
Injectable,
NotFoundException,
RequestTimeoutException,
} from '@nestjs/common';
import { Repository } from 'typeorm';
@@ -10,6 +12,8 @@ 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';
@Injectable()
export class TestsService {
@@ -54,4 +58,106 @@ export class TestsService {
});
}
}
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 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',
});
}
}
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',
});
}
}
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;
}
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 RequestTimeoutException('common.errors.requestTimeout', {
cause: err,
description: 'Error connecting to the database',
});
}
}
}
+25
View File
@@ -0,0 +1,25 @@
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';
import { TestsService } from './providers/tests.service';
import { Public } from '../auth/decorators/public.decorator';
@Controller('tests')
export class TestsController {
constructor(
/**
* Inject Tests Service
*/
private readonly testsService: TestsService,
) {}
@Public()
@Get()
public async getAllTests() {
return await this.testsService.userGetAll();
}
@Public()
@Get(':id')
public async getTestById(@Param('id', ParseIntPipe) id: number) {
return await this.testsService.userGetOne(id);
}
}
+2
View File
@@ -2,9 +2,11 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Test } from './entities/test.entity';
import { TestsService } from './providers/tests.service';
import { TestsController } from './tests.controller';
@Module({
imports: [TypeOrmModule.forFeature([Test])],
controllers: [TestsController],
providers: [TestsService],
exports: [TestsService],
})
@@ -0,0 +1,34 @@
import {
ValidationArguments,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { AccessType } from '../enums/access-types.enum';
import { I18nContext } from 'nestjs-i18n';
@ValidatorConstraint({ name: 'priceAccessType' })
export class PriceAccessTypeConstraint implements ValidatorConstraintInterface {
validate(
_: any,
validationArguments?: ValidationArguments,
): Promise<boolean> | boolean {
console.log('This is happening');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const obj = validationArguments?.object as any;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { price, accessType } = obj;
return (
(accessType === AccessType.PAID && price != null) ||
(accessType !== AccessType.PAID && price == null)
);
}
defaultMessage(): string {
const i18n = I18nContext.current();
return (
i18n?.t('tests.errors.priceAccessConstraint') ??
"Test's price depends to access type of 'Paid'."
);
}
}