103 lines
2.7 KiB
TypeScript
103 lines
2.7 KiB
TypeScript
import {
|
|
Body,
|
|
Controller,
|
|
Delete,
|
|
Get,
|
|
Param,
|
|
Post,
|
|
Put,
|
|
Query,
|
|
UseGuards
|
|
} from '@nestjs/common'
|
|
import { Todo } from '@prisma/client'
|
|
import { HasRoles } from 'src/auth/decorators/has-roles.decorator'
|
|
import { JwtAuthGuard } from 'src/auth/guards/jwt.authguard'
|
|
import { Role } from 'src/auth/guards/role.enum'
|
|
import { RolesGuard } from 'src/auth/guards/roles.guard'
|
|
import { TodoService } from './todo.service'
|
|
|
|
@Controller('todo')
|
|
export class TodoController {
|
|
constructor(private readonly todoService: TodoService) {}
|
|
|
|
@Get()
|
|
async fetchAll(@Query() query): Promise<any> {
|
|
console.log(query)
|
|
|
|
//Field별 filter AND Sql용
|
|
const filterSql = {}
|
|
console.log(filterSql)
|
|
|
|
//Field별 search OR Sql용
|
|
const searchFieldSQL = []
|
|
for (const index in query.searchFields) {
|
|
const temp = {
|
|
[query.searchFields[index]]: { contains: query.search as string }
|
|
}
|
|
searchFieldSQL.push(temp)
|
|
}
|
|
const searchSql = query.search ? { OR: searchFieldSQL } : {}
|
|
console.log(searchSql)
|
|
|
|
//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: { [query.sortBy]: query.sortDirection }
|
|
}
|
|
console.log(fetchSQL)
|
|
|
|
//전체 갯수 및 fetched Data
|
|
const total = await this.todoService.count(fetchSQL)
|
|
const rows = await this.todoService.fetchAll(fetchSQL)
|
|
const result = {
|
|
total: total,
|
|
perPage: perPage,
|
|
page: page + 1,
|
|
rows: rows
|
|
}
|
|
//console.log(result)
|
|
console.log('--------------------------------------------')
|
|
return result
|
|
}
|
|
|
|
@HasRoles(Role.USER)
|
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
@Get(':id')
|
|
async fetchOne(@Param('id') id: number): Promise<Todo | undefined> {
|
|
return await this.todoService.fetchOne(id)
|
|
}
|
|
|
|
@HasRoles(Role.USER)
|
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
@Delete(':id')
|
|
async delete(@Param('id') id: number): Promise<Todo | undefined> {
|
|
return await this.todoService.remove(id)
|
|
}
|
|
|
|
// @HasRoles(Role.USER)
|
|
// @UseGuards(JwtAuthGuard, RolesGuard)
|
|
//@UseGuards(JwtAuthGuard)
|
|
@Post()
|
|
async add(@Body() todo: Todo): Promise<Todo> {
|
|
return await this.todoService.add(todo)
|
|
}
|
|
|
|
@HasRoles(Role.USER)
|
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
@Put(':id')
|
|
async update(@Param('id') id: number, @Body() todo: Todo): Promise<Todo> {
|
|
return await this.todoService.update(id, todo)
|
|
}
|
|
}
|