Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(BE): 의과 약품 조회 API 구현 #47

Merged
merged 6 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 40 additions & 27 deletions backend/src/common/common.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import { BasePaginationDto } from './dto/base-pagination.dto';
import { FindManyOptions, FindOptionsOrder, Repository } from 'typeorm';
import { FindManyOptions, LessThan, MoreThan, Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseModel } from './entity/base.entity';

Expand All @@ -13,62 +13,75 @@ export class CommonService {
overrideFindOptions: FindManyOptions<T> = {},
) {
if (dto.page) {
return this.pagePaginate(dto, repository, overrideFindOptions);
return this.offsetPaginate(dto, repository, overrideFindOptions);
} else {
return this.cursorPaginate(dto, repository, overrideFindOptions);
}
}

private async pagePaginate<T extends BaseModel>(
private async offsetPaginate<T extends BaseModel>(
dto: BasePaginationDto,
repository: Repository<T>,
overrideFindOptions: FindManyOptions<T> = {},
) {
const findOptions = this.composeFindOptions<T>(dto);
const [data, count] = await repository.findAndCount({
...findOptions,
...overrideFindOptions,
});
const findOptions = this.composeFindOptions<T>(dto, overrideFindOptions);
const [data, count] = await repository.findAndCount(findOptions);

return {
data,
total: count,
data: data,
meta: {
total: count,
},
};
}

private async cursorPaginate<T extends BaseModel>(
async cursorPaginate<T extends BaseModel>(
dto: BasePaginationDto,
repository: Repository<T>,
overrideFindOptions: FindManyOptions<T> = {},
) {
const findOptions = this.composeFindOptions<T>(dto);
const findOptions = this.composeFindOptions<T>(dto, overrideFindOptions);
const [data, count] = await repository.findAndCount(findOptions);
let hasNext: boolean = true;
let cursor: number;

const results = await repository.find({
...findOptions,
...overrideFindOptions,
});
if (count <= dto.take || data.length <= 0) {
hasNext = false;
cursor = null;
} else {
cursor = data[data.length - 1].id;
}

return {
data: results,
count: results.length,
data: data,
meta: {
count: data.length,
cursor,
hasNext,
},
};
}

private composeFindOptions<T extends BaseModel>(
dto: BasePaginationDto,
overrideFindOptions: FindManyOptions<T> = {},
): FindManyOptions<T> {
let order: FindOptionsOrder<T> = {};
const { where, order, ...restOptions } = overrideFindOptions;

for (const [key] of Object.entries(dto)) {
if (key.startsWith('order__')) {
order = {
...order,
};
}
}
return {
order,
where: {
...(dto.cursor && {
id: dto.sort === 'ASC' ? MoreThan(dto.cursor) : LessThan(dto.cursor),
}),
...where,
},
order: {
createdAt: dto.sort,
...order,
},
take: dto.take,
skip: dto.page ? dto.take * (dto.page - 1) : null,
...restOptions,
};
}
}
25 changes: 20 additions & 5 deletions backend/src/common/dto/base-pagination.dto.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsIn, IsNumber, IsOptional } from 'class-validator';

export class BasePaginationDto {
@ApiPropertyOptional({
description: 'offset pagination',
})
@IsNumber()
@IsOptional()
page?: number;
page: number;

//정렬
// createdAt -> 생성된 시간의 내림차/오름차 순으로 정렬
@ApiPropertyOptional({
description: 'cursor pagination',
})
@IsNumber()
@IsOptional()
cursor: number;

@ApiPropertyOptional({
description: '정렬 <small>default: DESC</small>',
enum: ['ASC', 'DESC'],
})
@IsIn(['ASC', 'DESC'])
@IsOptional()
order__createdAt: 'ASC' | 'DESC' = 'ASC';
sort: 'ASC' | 'DESC' = 'DESC';

//몇개의 데이터를 응답을 받을지
@ApiPropertyOptional({
description: '응답 받을 데이터 개수 <small>default: 10</small>',
})
@IsNumber()
@IsOptional()
take: number = 10;
Expand Down
4 changes: 2 additions & 2 deletions backend/src/common/entity/base.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ export abstract class BaseModel {
@PrimaryGeneratedColumn()
id: number;

@UpdateDateColumn({ select: false })
@UpdateDateColumn()
updatedAt: Date;

@CreateDateColumn({ select: false })
@CreateDateColumn()
createdAt: Date;
}
26 changes: 26 additions & 0 deletions backend/src/m-medicines/dto/paginate-m-medicine.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsNumber, IsOptional, IsString } from 'class-validator';
import { BasePaginationDto } from 'src/common/dto/base-pagination.dto';

export class PaginateMMedicineDto extends BasePaginationDto {
@ApiPropertyOptional({
description: '약품 분류',
})
@IsNumber()
@IsOptional()
categoryId: number;

@ApiPropertyOptional({
description: '약품명',
})
@IsString()
@IsOptional()
name: string;

@ApiPropertyOptional({
description: '성분명/함량',
})
@IsString()
@IsOptional()
ingredient: string;
}
23 changes: 23 additions & 0 deletions backend/src/m-medicines/m-medicines.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
Param,
ParseIntPipe,
Patch,
Get,
Query,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
Expand All @@ -20,12 +22,33 @@ import {
import { MMedicinesService } from './m-medicines.service';
import { CreateMMedicineDto } from './dto/create-m-medicine.dto';
import { UpdateMMedicineDto } from './dto/update-m-medicine.dto';
import { PaginateMMedicineDto } from './dto/paginate-m-medicine.dto';

@ApiTags('의과')
@Controller('m/medicines')
export class MMedicinesController {
constructor(private readonly mMedicinesService: MMedicinesService) {}

@Get()
@ApiOperation({
summary: '약품 목록 조회',
description: 'offset pagination - page 쿼리 파라미터를 이용해야 합니다.',
})
async getMMedicines(@Query() paginateMMedicineDto: PaginateMMedicineDto) {
return this.mMedicinesService.paginateMedicines(paginateMMedicineDto);
}

@Get(':medicineId')
@ApiOperation({
summary: '약품 상세 조회',
})
@ApiResponse({
status: HttpStatus.NOT_FOUND,
})
async getMMedicine(@Param('medicineId', ParseIntPipe) medicineId: number) {
return this.mMedicinesService.getMedicine(medicineId);
}

@Post()
@UseInterceptors(FileInterceptor('image'))
@ApiConsumes('multipart/form-data')
Expand Down
6 changes: 5 additions & 1 deletion backend/src/m-medicines/m-medicines.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ import { MMedicinesController } from './m-medicines.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { M_Medicines } from './entity/m-medicines.entity';
import { M_Medicine_Categories } from 'src/m-medicine-categories/entity/m_medicine_categories.entity';
import { CommonModule } from 'src/common/common.module';

@Module({
imports: [TypeOrmModule.forFeature([M_Medicines, M_Medicine_Categories])],
imports: [
TypeOrmModule.forFeature([M_Medicines, M_Medicine_Categories]),
CommonModule,
],
controllers: [MMedicinesController],
providers: [MMedicinesService],
exports: [MMedicinesService],
Expand Down
39 changes: 38 additions & 1 deletion backend/src/m-medicines/m-medicines.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
Injectable,
NotFoundException,
} from '@nestjs/common';
import { Repository } from 'typeorm';
import { ILike, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { M_Medicines } from './entity/m-medicines.entity';
import { CreateMMedicineDto } from './dto/create-m-medicine.dto';
Expand All @@ -16,6 +16,8 @@ import {
import { ConfigService } from '@nestjs/config';
import { M_Medicine_Categories } from 'src/m-medicine-categories/entity/m_medicine_categories.entity';
import { UpdateMMedicineDto } from './dto/update-m-medicine.dto';
import { PaginateMMedicineDto } from './dto/paginate-m-medicine.dto';
import { CommonService } from 'src/common/common.service';

@Injectable()
export class MMedicinesService {
Expand All @@ -24,9 +26,44 @@ export class MMedicinesService {
private readonly mMedicinesRepository: Repository<M_Medicines>,
@InjectRepository(M_Medicine_Categories)
private readonly mMedicineCategoriesRepository: Repository<M_Medicine_Categories>,
private readonly commonService: CommonService,
private readonly configService: ConfigService,
) {}

async paginateMedicines(paginateDto: PaginateMMedicineDto) {
return this.commonService.paginate(paginateDto, this.mMedicinesRepository, {
where: {
...(paginateDto.name && { name: ILike(`%${paginateDto.name}%`) }),
...(paginateDto.ingredient && {
ingredient: ILike(`%${paginateDto.ingredient}%`),
}),
...(paginateDto.categoryId && {
category: { id: paginateDto.categoryId },
}),
},
relations: {
category: true,
},
});
}

async getMedicine(medicineId: number) {
const medicine = await this.mMedicinesRepository.findOne({
where: {
id: medicineId,
},
relations: {
category: true,
},
});

if (!medicine) {
throw new NotFoundException();
}

return medicine;
}

async createMMedicine(
medicineDto: CreateMMedicineDto,
image: Express.Multer.File,
Expand Down
Loading