NestJS 수정1..
This commit is contained in:
parent
741e47ac6e
commit
37df847d75
2
.env
2
.env
@ -11,5 +11,5 @@ JWT_SECURITY_KEY = "security_key"
|
|||||||
JWT_EXPIRE_MAX = "600s"
|
JWT_EXPIRE_MAX = "600s"
|
||||||
AUTH_USERNAME_FIELD="email"
|
AUTH_USERNAME_FIELD="email"
|
||||||
|
|
||||||
DEFAULT_TABLE_PER_PAGE = 5
|
DEFAULT_TABLE_PERPAGE = 5
|
||||||
DEFAULT_TABLE_PAGE = 1
|
DEFAULT_TABLE_PAGE = 1
|
||||||
|
|||||||
6
src/logger.middleware.ts
Normal file
6
src/logger.middleware.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express'
|
||||||
|
|
||||||
|
export function logger(req: Request, res: Response, next: NextFunction) {
|
||||||
|
console.log('Request...')
|
||||||
|
next()
|
||||||
|
}
|
||||||
36
src/main.ts
36
src/main.ts
@ -1,24 +1,36 @@
|
|||||||
//참고 : https://wikidocs.net/book/7059
|
//참고 : https://wikidocs.net/book/7059
|
||||||
|
|
||||||
|
import { HttpException, HttpStatus } from '@nestjs/common'
|
||||||
import { NestFactory } from '@nestjs/core'
|
import { NestFactory } from '@nestjs/core'
|
||||||
import { AppModule } from './app.module'
|
import { AppModule } from './app.module'
|
||||||
|
import { logger } from './logger.middleware'
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule)
|
|
||||||
//Enable All CORS Requests : https://docs.nestjs.com/security/cors
|
//Enable All CORS Requests : https://docs.nestjs.com/security/cors
|
||||||
const corsOptions = function (req, callback) {
|
const corsOptions = {
|
||||||
const origin = req.header('Origin')
|
origin: (origin, callback) => {
|
||||||
let corsOptions
|
//origin URL이 허용된 경우 또는 orgin자체가 없는 경우(postman tool) 통과
|
||||||
if (process.env.CORS_ALLOW_LIST.indexOf(origin) !== -1) {
|
if (process.env.CORS_ALLOW_LIST.includes(origin) || !origin) {
|
||||||
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
|
console.log(
|
||||||
console.log('Allowed Origin URL: ' + origin)
|
'Allowed Origin URL: ' + !origin ? 'JSON tool 사용' : origin
|
||||||
} else {
|
)
|
||||||
corsOptions = { origin: false } // disable CORS for this request
|
callback(null, true)
|
||||||
console.log('Not Allowed Origin URL: ' + origin)
|
} else {
|
||||||
|
callback(
|
||||||
|
new HttpException(
|
||||||
|
{
|
||||||
|
status: HttpStatus.FORBIDDEN,
|
||||||
|
error: origin + '에서는 접근이 허용되지 않습니다.'
|
||||||
|
},
|
||||||
|
HttpStatus.FORBIDDEN
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
callback(null, corsOptions) // callback expects two parameters: error and options
|
|
||||||
}
|
}
|
||||||
app.enableCors(corsOptions)
|
const app = await NestFactory.create(AppModule)
|
||||||
|
app.enableCors({ ...corsOptions })
|
||||||
|
//app.use(logger)
|
||||||
await app.listen(3000, function () {
|
await app.listen(3000, function () {
|
||||||
console.log(
|
console.log(
|
||||||
'[CORS-enabled->npm install -g webpack webpack-cli] web server listening on port 3000'
|
'[CORS-enabled->npm install -g webpack webpack-cli] web server listening on port 3000'
|
||||||
|
|||||||
@ -14,7 +14,6 @@ import { HasRoles } from 'src/auth/decorators/has-roles.decorator'
|
|||||||
import { JwtAuthGuard } from 'src/auth/guards/jwt.authguard'
|
import { JwtAuthGuard } from 'src/auth/guards/jwt.authguard'
|
||||||
import { Role } from 'src/auth/guards/role.enum'
|
import { Role } from 'src/auth/guards/role.enum'
|
||||||
import { RolesGuard } from 'src/auth/guards/roles.guard'
|
import { RolesGuard } from 'src/auth/guards/roles.guard'
|
||||||
import { TodoDTO } from './dtos/todo.dto'
|
|
||||||
import { TodoService } from './todo.service'
|
import { TodoService } from './todo.service'
|
||||||
|
|
||||||
@Controller('todo')
|
@Controller('todo')
|
||||||
@ -23,61 +22,81 @@ export class TodoController {
|
|||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
async fetchAll(@Query() query): Promise<any> {
|
async fetchAll(@Query() query): Promise<any> {
|
||||||
//Sql용
|
|
||||||
console.log(query)
|
console.log(query)
|
||||||
const searchSql = query.search
|
|
||||||
? {
|
|
||||||
OR: [
|
|
||||||
{ title: { contains: query.search as string } },
|
|
||||||
{ content: { contains: query.search as string } }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
: {}
|
|
||||||
|
|
||||||
|
//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
|
const page = query.page
|
||||||
? parseInt(query.page)
|
? parseInt(query.page) - 1
|
||||||
: parseInt(process.env.DEFAULT_TABLE_PAGE)
|
: parseInt(process.env.DEFAULT_TABLE_PAGE)
|
||||||
const per_page = query.per_page
|
const perPage = query.perPage
|
||||||
? parseInt(query.per_page)
|
? parseInt(query.perPage)
|
||||||
: parseInt(process.env.DEFAULT_TABLE_PER_PAGE)
|
: parseInt(process.env.DEFAULT_TABLE_PERPAGE)
|
||||||
const fetchSQL = {
|
const fetchSQL = {
|
||||||
skip: (page - 1) * per_page,
|
skip: page * perPage,
|
||||||
take: per_page,
|
take: perPage,
|
||||||
where: {
|
where: {
|
||||||
//is_done: true,
|
...filterSql,
|
||||||
...searchSql
|
...searchSql
|
||||||
},
|
},
|
||||||
orderBy: { id: 'desc' }
|
orderBy: { [query.sortBy]: query.sortDirectioin }
|
||||||
}
|
}
|
||||||
console.log(fetchSQL)
|
console.log(fetchSQL)
|
||||||
return this.todoService.fetchAll(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)
|
@HasRoles(Role.USER)
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
async fetchOne(@Param('id') id: number): Promise<Todo | undefined> {
|
async fetchOne(@Param('id') id: number): Promise<Todo | undefined> {
|
||||||
return this.todoService.fetchOne(id)
|
return await this.todoService.fetchOne(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@HasRoles(Role.USER)
|
@HasRoles(Role.USER)
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
async delete(@Param('id') id: number): Promise<Todo | undefined> {
|
async delete(@Param('id') id: number): Promise<Todo | undefined> {
|
||||||
return this.todoService.remove(id)
|
return await this.todoService.remove(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@HasRoles(Role.USER)
|
// @HasRoles(Role.USER)
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
// @UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
//@UseGuards(JwtAuthGuard)
|
||||||
@Post()
|
@Post()
|
||||||
async add(@Body() data: Todo): Promise<Todo> {
|
async add(@Body() todo: Todo): Promise<Todo> {
|
||||||
return this.todoService.add(data)
|
return await this.todoService.add(todo)
|
||||||
}
|
}
|
||||||
|
|
||||||
@HasRoles(Role.USER)
|
@HasRoles(Role.USER)
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
@Put(':id')
|
@Put(':id')
|
||||||
async update(@Param('id') id: number, @Body() data: TodoDTO): Promise<Todo> {
|
async update(@Param('id') id: number, @Body() todo: Todo): Promise<Todo> {
|
||||||
return this.todoService.update(id, data)
|
return await this.todoService.update(id, todo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,43 +1,67 @@
|
|||||||
import { Injectable } from '@nestjs/common'
|
import { Injectable } from '@nestjs/common'
|
||||||
import { Todo } from '@prisma/client'
|
import { Prisma, Todo } from '@prisma/client'
|
||||||
import { PrismaService } from 'src/prisma.service'
|
import { PrismaService } from 'src/prisma.service'
|
||||||
import { TodoDTO } from './dtos/todo.dto'
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TodoService {
|
export class TodoService {
|
||||||
todo: any
|
constructor(private prisma: PrismaService) {}
|
||||||
constructor(private prismaService: PrismaService) {}
|
|
||||||
|
|
||||||
//참고: https://intrepidgeeks.com/tutorial/05-instagram-clone-code-5-user-summary
|
//참고: https://intrepidgeeks.com/tutorial/05-instagram-clone-code-5-user-summary
|
||||||
//전체조회
|
//전체조회
|
||||||
async count(sql: any): Promise<number> {
|
async count(params: {
|
||||||
return this.prismaService.todo.count(sql)
|
skip?: number
|
||||||
|
take?: number
|
||||||
|
cursor?: Prisma.TodoWhereUniqueInput
|
||||||
|
where?: Prisma.TodoWhereInput
|
||||||
|
orderBy?: Prisma.TodoOrderByWithRelationInput
|
||||||
|
}): Promise<number> {
|
||||||
|
const { skip, take, cursor, where, orderBy } = params
|
||||||
|
return this.prisma.todo.count({
|
||||||
|
cursor,
|
||||||
|
where,
|
||||||
|
orderBy
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetchAll(sql: any): Promise<Todo[]> {
|
async fetchAll(params: {
|
||||||
return this.prismaService.todo.findMany(sql)
|
skip?: number
|
||||||
|
take?: number
|
||||||
|
cursor?: Prisma.TodoWhereUniqueInput
|
||||||
|
where?: Prisma.TodoWhereInput
|
||||||
|
orderBy?: Prisma.TodoOrderByWithRelationInput
|
||||||
|
}): Promise<Todo[]> {
|
||||||
|
const { skip, take, cursor, where, orderBy } = params
|
||||||
|
return this.prisma.todo.findMany({
|
||||||
|
skip,
|
||||||
|
take,
|
||||||
|
cursor,
|
||||||
|
where,
|
||||||
|
orderBy
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 조회
|
//단일 조회
|
||||||
async fetchOne(id: number): Promise<Todo | undefined> {
|
async fetchOne(id: number): Promise<Todo | undefined> {
|
||||||
return this.prismaService.todo.findUnique({ where: { id: Number(id) } })
|
return this.prisma.todo.findUnique({
|
||||||
|
where: { id: Number(id) }
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 삭제
|
//단일 삭제
|
||||||
async remove(id: number): Promise<Todo | undefined> {
|
async remove(id: number): Promise<Todo | undefined> {
|
||||||
return this.prismaService.todo.delete({ where: { id: Number(id) } })
|
return this.prisma.todo.delete({ where: { id: Number(id) } })
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 추가
|
//단일 추가
|
||||||
async add(data: Todo): Promise<Todo> {
|
async add(todo: Prisma.TodoCreateInput): Promise<Todo> {
|
||||||
return this.prismaService.todo.create({ data: data })
|
return this.prisma.todo.create({ data: todo })
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 수정
|
//단일 수정
|
||||||
async update(id: number, data: TodoDTO): Promise<Todo | undefined> {
|
async update(id: number, todo: Todo): Promise<Todo | undefined> {
|
||||||
return this.prismaService.todo.update({
|
return this.prisma.todo.update({
|
||||||
where: { id: Number(id) },
|
where: { id: Number(id) },
|
||||||
data: data
|
data: todo
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,36 +5,36 @@ import { UserDTO } from './dtos/user.dto'
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UserService {
|
export class UserService {
|
||||||
constructor(private prismaService: PrismaService) {}
|
constructor(private prisma: PrismaService) {}
|
||||||
|
|
||||||
//단일 조회 ByEmail
|
//단일 조회 ByEmail
|
||||||
async fetchOneByEmail(email: string): Promise<User | undefined> {
|
async fetchOneByEmail(email: string): Promise<User | undefined> {
|
||||||
return this.prismaService.user.findUnique({ where: { email: email } })
|
return this.prisma.user.findUnique({ where: { email: email } })
|
||||||
}
|
}
|
||||||
|
|
||||||
//전체조회
|
//전체조회
|
||||||
async fetchAll(sql: any): Promise<User[]> {
|
async fetchAll(sql: any): Promise<User[]> {
|
||||||
return this.prismaService.user.findMany(sql)
|
return this.prisma.user.findMany(sql)
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 조회
|
//단일 조회
|
||||||
async fetchOne(id: number): Promise<User | undefined> {
|
async fetchOne(id: number): Promise<User | undefined> {
|
||||||
return this.prismaService.user.findUnique({ where: { id: Number(id) } })
|
return this.prisma.user.findUnique({ where: { id: Number(id) } })
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 삭제
|
//단일 삭제
|
||||||
async remove(id: number): Promise<User | undefined> {
|
async remove(id: number): Promise<User | undefined> {
|
||||||
return this.prismaService.user.delete({ where: { id: Number(id) } })
|
return this.prisma.user.delete({ where: { id: Number(id) } })
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 추가
|
//단일 추가
|
||||||
async add(data: User): Promise<User> {
|
async add(data: User): Promise<User> {
|
||||||
return this.prismaService.user.create({ data: data })
|
return this.prisma.user.create({ data: data })
|
||||||
}
|
}
|
||||||
|
|
||||||
//단일 수정
|
//단일 수정
|
||||||
async update(id: number, data: UserDTO): Promise<User | undefined> {
|
async update(id: number, data: UserDTO): Promise<User | undefined> {
|
||||||
return this.prismaService.user.update({
|
return this.prisma.user.update({
|
||||||
where: { id: Number(id) },
|
where: { id: Number(id) },
|
||||||
data: data
|
data: data
|
||||||
})
|
})
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user