add angular list view generations

This commit is contained in:
Roland Schneider
2025-11-19 09:52:15 +01:00
parent 8ccb75ee4e
commit 997dd917fe
16 changed files with 495 additions and 5 deletions

View File

@@ -9,6 +9,8 @@ import { User } from './entity/user';
import { UserGroup } from './entity/user-group';
import { UserRole } from './entity/user-role';
import { LoggerModule } from './logger/logger.module';
import { Product } from "./entity/product.entity";
import { ProductsModule } from "./product/products.module";
const moduleTypeOrm = TypeOrmModule.forRootAsync({
imports: [ConfigModule],
@@ -21,7 +23,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, Product],
logging: true,
// synchronize: true,
};
@@ -35,7 +37,8 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
UserModule,
AuthModule,
LoggerModule,
],
ProductsModule
],
controllers: [AppController],
providers: [AppService],
})

View 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;
}

View File

@@ -0,0 +1,5 @@
import { OmitType } from '@nestjs/mapped-types';
import { Product } from '../../entity/product.entity';
// NOTE: Use class-validator decorators here for production-grade validation.
export class CreateProductDto extends OmitType(Product, ['id']) {}

View File

@@ -0,0 +1,32 @@
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; // Should be a property of the Product entity
@IsOptional()
@IsIn(['ASC', 'DESC'])
order?: 'ASC' | 'DESC';
// --- Add other filterable properties below ---
// @IsOptional()
// @IsString()
// name?: string;
// @IsOptional()
// @Type(() => Boolean)
// @IsBoolean()
// is_available?: boolean;
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateProductDto } from './create-product.dto';
export class UpdateProductDto extends PartialType(CreateProductDto) {}

View File

@@ -0,0 +1,35 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, ParseIntPipe } 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(':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);
}
}

View 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 {}

View File

@@ -0,0 +1,108 @@
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>,
) {}
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[] = [
// Example: { param: 'name', dbField: 'name', operator: 'like' },
// Example: { param: 'is_available', dbField: 'is_available', operator: 'equals' },
];
// --- START OF THE FIX ---
// 1. Create a loosely typed object to build the where clause.
const whereClause: { [key: string]: any } = {};
// 2. Populate it dynamically. This avoids the TypeScript error.
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];
}
}
}
// 3. Assign the complete, built clause to the strongly-typed options.
const findOptions: FindManyOptions<Product> = {
where: whereClause as FindOptionsWhere<Product>,
};
// --- END OF THE FIX ---
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 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 };
}
}