add product and entity type
This commit is contained in:
@@ -33,7 +33,7 @@ Accept: application/json
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "p3",
|
||||
"name": "p22",
|
||||
"price": 3,
|
||||
"is_available": true
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@ import { User } from './entity/user';
|
||||
import { UserGroup } from './entity/user-group';
|
||||
import { UserRole } from './entity/user-role';
|
||||
import { LoggerModule } from './logger/logger.module';
|
||||
import { EventType } from './entity/event-type.entity';
|
||||
import { EventTypesModule } from './event-type/event-type.module';
|
||||
import { Product } from './entity/product.entity';
|
||||
import { ProductsModule } from './product/products.module';
|
||||
|
||||
const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
@@ -21,7 +25,7 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
username: configService.get<string>('DATABASE_USER'),
|
||||
password: configService.get<string>('DATABASE_PASS'),
|
||||
database: configService.get<string>('DATABASE_NAME'),
|
||||
entities: [User, UserGroup, UserRole],
|
||||
entities: [User, UserGroup, UserRole, EventType, Product],
|
||||
logging: true,
|
||||
// synchronize: true,
|
||||
};
|
||||
@@ -35,6 +39,8 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
UserModule,
|
||||
AuthModule,
|
||||
LoggerModule,
|
||||
EventTypesModule,
|
||||
ProductsModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
||||
@@ -5,6 +5,7 @@ import { User } from './entity/user';
|
||||
import * as dotenv from 'dotenv';
|
||||
import { UserGroup } from './entity/user-group';
|
||||
import { UserRole } from './entity/user-role';
|
||||
import { EventType } from './entity/event-type.entity';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
@@ -17,7 +18,7 @@ export const AppDataSource = new DataSource({
|
||||
database: process.env.DATABASE_NAME,
|
||||
synchronize: false,
|
||||
logging: false,
|
||||
entities: [User, UserGroup, UserRole],
|
||||
entities: [User, UserGroup, UserRole, EventType],
|
||||
migrations: [
|
||||
'src/migration/**/*.ts'
|
||||
],
|
||||
|
||||
23
server/src/entity/event-type.entity.ts
Normal file
23
server/src/entity/event-type.entity.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||
import { IsString, IsNumber, IsBoolean, IsDate, IsOptional } from 'class-validator';
|
||||
|
||||
@Entity({ name: 'event_type' })
|
||||
export class EventType {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@Column({ type: 'character varying', nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'character varying', nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
color: string | null;
|
||||
|
||||
}
|
||||
23
server/src/entity/product.entity.ts
Normal file
23
server/src/entity/product.entity.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||
import { IsString, IsNumber, IsBoolean, IsDate, IsOptional } from 'class-validator';
|
||||
|
||||
@Entity({ name: 'products' })
|
||||
export class Product {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@Column({ type: 'numeric', nullable: true })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
price: number | null;
|
||||
|
||||
@Column({ type: 'boolean', nullable: true, default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
is_available: boolean | null = true;
|
||||
|
||||
}
|
||||
4
server/src/event-type/dto/create-event-type.dto.ts
Normal file
4
server/src/event-type/dto/create-event-type.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { OmitType } from '@nestjs/mapped-types';
|
||||
import { EventType } from '../../entity/event-type.entity';
|
||||
|
||||
export class CreateEventTypeDto extends OmitType(EventType, ['id']) {}
|
||||
9
server/src/event-type/dto/query-event-type.dto.ts
Normal file
9
server/src/event-type/dto/query-event-type.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsOptional, IsString, IsNumber, IsIn, IsBoolean } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class QueryEventTypeDto {
|
||||
@IsOptional() @Type(() => Number) @IsNumber() page?: number;
|
||||
@IsOptional() @Type(() => Number) @IsNumber() limit?: number;
|
||||
@IsOptional() @IsString() sortBy?: string;
|
||||
@IsOptional() @IsIn(['ASC', 'DESC']) order?: 'ASC' | 'DESC';
|
||||
}
|
||||
4
server/src/event-type/dto/update-event-type.dto.ts
Normal file
4
server/src/event-type/dto/update-event-type.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateEventTypeDto } from './create-event-type.dto';
|
||||
|
||||
export class UpdateEventTypeDto extends PartialType(CreateEventTypeDto) {}
|
||||
44
server/src/event-type/event-type.controller.ts
Normal file
44
server/src/event-type/event-type.controller.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, ParseIntPipe, DefaultValuePipe } from '@nestjs/common';
|
||||
import { EventTypesService } from './event-type.service';
|
||||
import { CreateEventTypeDto } from './dto/create-event-type.dto';
|
||||
import { UpdateEventTypeDto } from './dto/update-event-type.dto';
|
||||
import { QueryEventTypeDto } from './dto/query-event-type.dto';
|
||||
|
||||
@Controller('event-type')
|
||||
export class EventTypesController {
|
||||
constructor(private readonly eventTypesService: EventTypesService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() createEventTypeDto: CreateEventTypeDto) {
|
||||
return this.eventTypesService.create(createEventTypeDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(@Query() queryParams: QueryEventTypeDto) {
|
||||
return this.eventTypesService.findAll(queryParams);
|
||||
}
|
||||
|
||||
@Get('search')
|
||||
search(
|
||||
@Query('q') term: string,
|
||||
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
|
||||
@Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,
|
||||
) {
|
||||
return this.eventTypesService.search(term, { page, limit });
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.eventTypesService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() updateEventTypeDto: UpdateEventTypeDto) {
|
||||
return this.eventTypesService.update(id, updateEventTypeDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.eventTypesService.remove(id);
|
||||
}
|
||||
}
|
||||
12
server/src/event-type/event-type.module.ts
Normal file
12
server/src/event-type/event-type.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { EventTypesService } from './event-type.service';
|
||||
import { EventTypesController } from './event-type.controller';
|
||||
import { EventType } from '../entity/event-type.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([EventType])],
|
||||
controllers: [EventTypesController],
|
||||
providers: [EventTypesService],
|
||||
})
|
||||
export class EventTypesModule {}
|
||||
103
server/src/event-type/event-type.service.ts
Normal file
103
server/src/event-type/event-type.service.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, FindManyOptions, FindOptionsWhere, ILike } from 'typeorm';
|
||||
import { CreateEventTypeDto } from './dto/create-event-type.dto';
|
||||
import { UpdateEventTypeDto } from './dto/update-event-type.dto';
|
||||
import { QueryEventTypeDto } from './dto/query-event-type.dto';
|
||||
import { EventType } from '../entity/event-type.entity';
|
||||
|
||||
type QueryConfigItem = {
|
||||
param: keyof Omit<QueryEventTypeDto, 'page' | 'limit' | 'sortBy' | 'order'>;
|
||||
dbField: keyof EventType;
|
||||
operator: 'equals' | 'like';
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class EventTypesService {
|
||||
constructor(
|
||||
@InjectRepository(EventType)
|
||||
private readonly eventTypeRepository: Repository<EventType>,
|
||||
) {}
|
||||
|
||||
private readonly searchableFields: (keyof EventType)[] = [
|
||||
'name',
|
||||
'description',
|
||||
'color'
|
||||
];
|
||||
|
||||
create(createEventTypeDto: CreateEventTypeDto) {
|
||||
const newRecord = this.eventTypeRepository.create(createEventTypeDto);
|
||||
return this.eventTypeRepository.save(newRecord);
|
||||
}
|
||||
|
||||
async findAll(queryParams: QueryEventTypeDto) {
|
||||
const { page = 1, limit = 0, sortBy, order, ...filters } = queryParams;
|
||||
const queryConfig: QueryConfigItem[] = [];
|
||||
const whereClause: { [key: string]: any } = {};
|
||||
for (const config of queryConfig) {
|
||||
if (filters[config.param] !== undefined) {
|
||||
if (config.operator === 'like') {
|
||||
whereClause[config.dbField] = ILike(`%${filters[config.param]}%`);
|
||||
} else {
|
||||
whereClause[config.dbField] = filters[config.param];
|
||||
}
|
||||
}
|
||||
}
|
||||
const findOptions: FindManyOptions<EventType> = { where: whereClause as FindOptionsWhere<EventType> };
|
||||
const paginated = limit > 0;
|
||||
if (paginated) {
|
||||
findOptions.skip = (page - 1) * limit;
|
||||
findOptions.take = limit;
|
||||
}
|
||||
if (sortBy && order) {
|
||||
findOptions.order = { [sortBy]: order };
|
||||
}
|
||||
const [data, totalItems] = await this.eventTypeRepository.findAndCount(findOptions);
|
||||
if (!paginated) {
|
||||
return { data, total: data.length };
|
||||
}
|
||||
return {
|
||||
data,
|
||||
meta: { totalItems, itemCount: data.length, itemsPerPage: limit, totalPages: Math.ceil(totalItems / limit), currentPage: page },
|
||||
};
|
||||
}
|
||||
|
||||
async search(term: string, options: { page: number; limit: number }) {
|
||||
if (this.searchableFields.length === 0) {
|
||||
console.warn('Search is not configured for this entity.');
|
||||
return { data: [], meta: { totalItems: 0, itemCount: 0, itemsPerPage: options.limit, totalPages: 0, currentPage: options.page } };
|
||||
}
|
||||
const whereConditions = this.searchableFields.map(field => ({ [field]: ILike(`%${term}%`) }));
|
||||
const [data, totalItems] = await this.eventTypeRepository.findAndCount({
|
||||
where: whereConditions,
|
||||
skip: (options.page - 1) * options.limit,
|
||||
take: options.limit,
|
||||
});
|
||||
return {
|
||||
data,
|
||||
meta: { totalItems, itemCount: data.length, itemsPerPage: options.limit, totalPages: Math.ceil(totalItems / options.limit), currentPage: options.page },
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const record = await this.eventTypeRepository.findOneBy({ id: id as any });
|
||||
if (!record) {
|
||||
throw new NotFoundException(`EventType with ID ${id} not found`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
async update(id: number, updateEventTypeDto: UpdateEventTypeDto) {
|
||||
const record = await this.findOne(id);
|
||||
Object.assign(record, updateEventTypeDto);
|
||||
return this.eventTypeRepository.save(record);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const result = await this.eventTypeRepository.delete(id);
|
||||
if (result.affected === 0) {
|
||||
throw new NotFoundException(`EventType with ID ${id} not found`);
|
||||
}
|
||||
return { deleted: true, id };
|
||||
}
|
||||
}
|
||||
22
server/src/migration/1763106308121-add_event_type_table.ts
Normal file
22
server/src/migration/1763106308121-add_event_type_table.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
export class AddEventTypeTable1763106308121 implements MigrationInterface {
|
||||
name = 'AddEventTypeTable1763106308121';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "event_type"
|
||||
(
|
||||
"id" SERIAL NOT NULL,
|
||||
"name" character varying NOT NULL,
|
||||
"description" character varying NULL,
|
||||
"color" character varying NULL,
|
||||
CONSTRAINT "PK_event_type_id" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "U_event_type_name" UNIQUE ("name"))`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP TABLE "event_type"`);
|
||||
}
|
||||
}
|
||||
4
server/src/product/dto/create-product.dto.ts
Normal file
4
server/src/product/dto/create-product.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { OmitType } from '@nestjs/mapped-types';
|
||||
import { Product } from '../../entity/product.entity';
|
||||
|
||||
export class CreateProductDto extends OmitType(Product, ['id']) {}
|
||||
9
server/src/product/dto/query-product.dto.ts
Normal file
9
server/src/product/dto/query-product.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsOptional, IsString, IsNumber, IsIn, IsBoolean } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class QueryProductDto {
|
||||
@IsOptional() @Type(() => Number) @IsNumber() page?: number;
|
||||
@IsOptional() @Type(() => Number) @IsNumber() limit?: number;
|
||||
@IsOptional() @IsString() sortBy?: string;
|
||||
@IsOptional() @IsIn(['ASC', 'DESC']) order?: 'ASC' | 'DESC';
|
||||
}
|
||||
4
server/src/product/dto/update-product.dto.ts
Normal file
4
server/src/product/dto/update-product.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateProductDto } from './create-product.dto';
|
||||
|
||||
export class UpdateProductDto extends PartialType(CreateProductDto) {}
|
||||
44
server/src/product/products.controller.ts
Normal file
44
server/src/product/products.controller.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, ParseIntPipe, DefaultValuePipe } from '@nestjs/common';
|
||||
import { ProductsService } from './products.service';
|
||||
import { CreateProductDto } from './dto/create-product.dto';
|
||||
import { UpdateProductDto } from './dto/update-product.dto';
|
||||
import { QueryProductDto } from './dto/query-product.dto';
|
||||
|
||||
@Controller('products')
|
||||
export class ProductsController {
|
||||
constructor(private readonly productsService: ProductsService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() createProductDto: CreateProductDto) {
|
||||
return this.productsService.create(createProductDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(@Query() queryParams: QueryProductDto) {
|
||||
return this.productsService.findAll(queryParams);
|
||||
}
|
||||
|
||||
@Get('search')
|
||||
search(
|
||||
@Query('q') term: string,
|
||||
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
|
||||
@Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,
|
||||
) {
|
||||
return this.productsService.search(term, { page, limit });
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.productsService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() updateProductDto: UpdateProductDto) {
|
||||
return this.productsService.update(id, updateProductDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.productsService.remove(id);
|
||||
}
|
||||
}
|
||||
12
server/src/product/products.module.ts
Normal file
12
server/src/product/products.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ProductsService } from './products.service';
|
||||
import { ProductsController } from './products.controller';
|
||||
import { Product } from '../entity/product.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Product])],
|
||||
controllers: [ProductsController],
|
||||
providers: [ProductsService],
|
||||
})
|
||||
export class ProductsModule {}
|
||||
104
server/src/product/products.service.ts
Normal file
104
server/src/product/products.service.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, FindManyOptions, FindOptionsWhere, ILike } from 'typeorm';
|
||||
import { CreateProductDto } from './dto/create-product.dto';
|
||||
import { UpdateProductDto } from './dto/update-product.dto';
|
||||
import { QueryProductDto } from './dto/query-product.dto';
|
||||
import { Product } from '../entity/product.entity';
|
||||
|
||||
type QueryConfigItem = {
|
||||
param: keyof Omit<QueryProductDto, 'page' | 'limit' | 'sortBy' | 'order'>;
|
||||
dbField: keyof Product;
|
||||
operator: 'equals' | 'like';
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class ProductsService {
|
||||
constructor(
|
||||
@InjectRepository(Product)
|
||||
private readonly productRepository: Repository<Product>,
|
||||
) {}
|
||||
|
||||
private readonly searchableFields: (keyof Product)[] = [
|
||||
'name'
|
||||
];
|
||||
|
||||
create(createProductDto: CreateProductDto) {
|
||||
const newRecord = this.productRepository.create(createProductDto);
|
||||
return this.productRepository.save(newRecord);
|
||||
}
|
||||
|
||||
async findAll(queryParams: QueryProductDto) {
|
||||
const { page = 1, limit = 0, sortBy, order, ...filters } = queryParams;
|
||||
const queryConfig: QueryConfigItem[] = [];
|
||||
const whereClause: { [key: string]: any } = {};
|
||||
for (const config of queryConfig) {
|
||||
if (filters[config.param] !== undefined) {
|
||||
if (config.operator === 'like') {
|
||||
whereClause[config.dbField] = ILike(`%${filters[config.param]}%`);
|
||||
} else {
|
||||
whereClause[config.dbField] = filters[config.param];
|
||||
}
|
||||
}
|
||||
}
|
||||
const findOptions: FindManyOptions<Product> = { where: whereClause as FindOptionsWhere<Product> };
|
||||
const paginated = limit > 0;
|
||||
if (paginated) {
|
||||
findOptions.skip = (page - 1) * limit;
|
||||
findOptions.take = limit;
|
||||
}
|
||||
if (sortBy && order) {
|
||||
findOptions.order = { [sortBy]: order };
|
||||
}
|
||||
const [data, totalItems] = await this.productRepository.findAndCount(findOptions);
|
||||
if (!paginated) {
|
||||
return { data, total: data.length };
|
||||
}
|
||||
return {
|
||||
data,
|
||||
meta: { totalItems, itemCount: data.length, itemsPerPage: limit, totalPages: Math.ceil(totalItems / limit), currentPage: page },
|
||||
};
|
||||
}
|
||||
|
||||
async search(term: string, options: { page: number; limit: number }) {
|
||||
if (!term || term.trim() === '') {
|
||||
return { data: [], meta: { totalItems: 0, itemCount: 0, itemsPerPage: options.limit, totalPages: 0, currentPage: options.page } };
|
||||
}
|
||||
if (this.searchableFields.length === 0) {
|
||||
console.warn('Search is not configured for this entity.');
|
||||
return { data: [], meta: { totalItems: 0, itemCount: 0, itemsPerPage: options.limit, totalPages: 0, currentPage: options.page } };
|
||||
}
|
||||
const whereConditions = this.searchableFields.map(field => ({ [field]: ILike(`%${term}%`) }));
|
||||
const [data, totalItems] = await this.productRepository.findAndCount({
|
||||
where: whereConditions,
|
||||
skip: (options.page - 1) * options.limit,
|
||||
take: options.limit,
|
||||
});
|
||||
return {
|
||||
data,
|
||||
meta: { totalItems, itemCount: data.length, itemsPerPage: options.limit, totalPages: Math.ceil(totalItems / options.limit), currentPage: options.page },
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const record = await this.productRepository.findOneBy({ id: id as any });
|
||||
if (!record) {
|
||||
throw new NotFoundException(`Product with ID ${id} not found`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
async update(id: number, updateProductDto: UpdateProductDto) {
|
||||
const record = await this.findOne(id);
|
||||
Object.assign(record, updateProductDto);
|
||||
return this.productRepository.save(record);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const result = await this.productRepository.delete(id);
|
||||
if (result.affected === 0) {
|
||||
throw new NotFoundException(`Product with ID ${id} not found`);
|
||||
}
|
||||
return { deleted: true, id };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user