import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common' import { Todo } from '@prisma/client' import { TodoDTO } from './dtos/todo.dto' import { TodoService } from './todo.service' @Controller('todo') export class TodoController { constructor(private readonly todoService: TodoService) {} @Get() fetchAll(@Query() query) { console.log(query) //Field별 filter AND Sql용 let filterSql = {} switch (query.filterField) { case 'is_done': if (query.filter) { filterSql = { AND: { [query.filterField]: query.filter === 'true' ? true : false } } } break case 'updatedAt': case 'createdAt': if (query.filterDateStart && query.filterDateEnd) { filterSql = { AND: { [query.filterField]: { gte: new Date(query.filterDateStart) as Date, lte: new Date(query.filterDateEnd) as Date } } } } break } console.log(filterSql) //Field별 search OR Sql용 let searchSql = {} if (query.search) { const searchFieldSQLs = [] for (const index in query.searchFields) { switch (query.searchFields[index]) { case 'title': case 'content': searchFieldSQLs.push({ [query.searchFields[index]]: { contains: query.search as string } }) break case 'updatedAt': case 'createdAt': searchFieldSQLs.push({ [query.searchFields[index]]: { gte: new Date(query.search) as Date } }) break } } console.log(searchFieldSQLs) searchSql = { OR: searchFieldSQLs } } console.log(searchSql) //Field별 Sort Sql용 if (!query.sortBy) { query.sortBy = 'id' } const orderBySql = { [query.sortBy]: query.sortDesc === 'true' ? 'desc' : 'asc' } console.log(orderBySql) //fetch SQL용 const page = query.page ? parseInt(query.page) - 1 : parseInt(process.env.DEFAULT_TABLE_PAGE) const perPage = query.perPage ? parseInt(query.perPage) : parseInt(process.env.DEFAULT_TABLE_PERPAGE) const fetchSQL = { skip: page * perPage, take: perPage, where: { ...filterSql, ...searchSql }, orderBy: orderBySql } console.log(fetchSQL) //전체 갯수 및 fetched Data const total = this.todoService.count(fetchSQL) const rows = this.todoService.fetchAll(fetchSQL) const result = { total: total, perPage: perPage, page: page + 1, sortBy: query.sortBy, sortDesc: query.sortDesc, rows: rows } //console.log(result) console.log('--------------------------------------------') return result } @Get(':id') fetchOne(@Param('id') id: string): Promise { return this.todoService.fetchOne({ id: Number(id) }) } @Post() add(@Body() data: TodoDTO): Promise { return this.todoService.add(data) } @Put(':id') update(@Param('id') id: string, @Body() data: TodoDTO): Promise { data.updatedAt = new Date() return this.todoService.update({ where: { id: Number(id) }, data: data }) } @Delete(':id') delete(@Param('id') id: string): Promise { return this.todoService.remove({ id: Number(id) }) } }