NestJS 수정1..

This commit is contained in:
최준흠 2022-08-31 17:10:31 +09:00
parent d0d587e966
commit db41767505
5 changed files with 70 additions and 26 deletions

3
.env
View File

@ -5,7 +5,8 @@
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="mysql://root:@localhost:3306/test" DATABASE_URL="mysql://root:@localhost:3306/test"
CORS_ALLOW_LIST = ['http://localhost:8080'] CORS_ALLOW_ORIGINS = ['http://localhost:8080']
CORS_ALLOW_METHOD = "GET,PUT,POST,DELETE,PATCH,OPTIONS"
JWT_SECURITY_KEY = "security_key" JWT_SECURITY_KEY = "security_key"
JWT_EXPIRE_MAX = "600s" JWT_EXPIRE_MAX = "600s"

View File

@ -3,17 +3,15 @@
import { HttpException, HttpStatus } from '@nestjs/common' 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 = { app.enableCors({
origin: (origin, callback) => { origin: (origin, callback) => {
//origin URL이 허용된 경우 또는 orgin자체가 없는 경우(postman tool) 통과 //origin URL이 허용된 경우 또는 orgin자체가 없는 경우(postman tool) 통과
if (process.env.CORS_ALLOW_LIST.includes(origin) || !origin) { if (process.env.CORS_ALLOW_ORIGINS.indexOf(origin) !== -1 || !origin) {
console.log( console.log('Allowed Origin URL: ' + origin)
'Allowed Origin URL: ' + !origin ? 'JSON tool 사용' : origin
)
callback(null, true) callback(null, true)
} else { } else {
callback( callback(
@ -26,10 +24,10 @@ async function bootstrap() {
) )
) )
} }
} },
} methods: process.env.CORS_ALLOW_METHOD,
const app = await NestFactory.create(AppModule) credentials: true
app.enableCors({ ...corsOptions }) })
//app.use(logger) //app.use(logger)
await app.listen(3000, function () { await app.listen(3000, function () {
console.log( console.log(

View File

@ -3,12 +3,27 @@ import { PrismaClient } from '@prisma/client'
@Injectable() @Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit { export class PrismaService extends PrismaClient implements OnModuleInit {
constructor() {
//SQL 로그를 출력하기위해 추가
super({
log: [
{ emit: 'event', level: 'query' },
{ emit: 'stdout', level: 'info' },
{ emit: 'stdout', level: 'warn' },
{ emit: 'stdout', level: 'error' }
],
errorFormat: 'colorless'
})
}
async onModuleInit() { async onModuleInit() {
await this.$connect() await this.$connect()
} }
async enableShutdownHooks(app: INestApplication) { async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => { this.$on('beforeExit', async (event) => {
//SQL 로그를 출력하기위해 추가
console.log(event.name)
await app.close() await app.close()
}) })
} }

View File

@ -26,18 +26,42 @@ export class TodoController {
console.log(query) console.log(query)
//Field별 filter AND Sql용 //Field별 filter AND Sql용
const filterSql = {} let filterSql = {}
switch (query.filterField) {
case 'is_done':
if (query.filter) {
filterSql = {
AND: {
[query.filterField]: query.filter
}
}
}
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) console.log(filterSql)
//Field별 search OR Sql용 //Field별 search OR Sql용
let searchSql = {} let searchSql = {}
if (query.search) { if (query.search) {
const searchFieldSQL = [] const searchFieldSQLs = []
for (const index in query.searchFields) { for (const index in query.searchFields) {
switch (query.searchFields[index]) { switch (query.searchFields[index]) {
case 'title': case 'title':
case 'content': case 'content':
searchFieldSQL.push({ searchFieldSQLs.push({
[query.searchFields[index]]: { [query.searchFields[index]]: {
contains: query.search as string contains: query.search as string
} }
@ -45,19 +69,23 @@ export class TodoController {
break break
case 'updatedAt': case 'updatedAt':
case 'createdAt': case 'createdAt':
searchFieldSQL.push({ searchFieldSQLs.push({
[query.searchFields[index]]: { [query.searchFields[index]]: {
gte: new Date(query.search) as Date gte: new Date(query.search) as Date
} }
}) })
break break
} }
console.log(searchFieldSQL)
} }
searchSql = { OR: searchFieldSQL } console.log(searchFieldSQLs)
console.log(searchSql) searchSql = { OR: searchFieldSQLs }
} }
console.log(searchSql)
//Field별 Sort Sql용
if (!query.sortBy) {
query.sortBy = 'id'
}
const orderBySql = { const orderBySql = {
[query.sortBy]: query.sortDesc === 'true' ? 'desc' : 'asc' [query.sortBy]: query.sortDesc === 'true' ? 'desc' : 'asc'
} }
@ -70,6 +98,7 @@ export class TodoController {
const perPage = query.perPage const perPage = query.perPage
? parseInt(query.perPage) ? parseInt(query.perPage)
: parseInt(process.env.DEFAULT_TABLE_PERPAGE) : parseInt(process.env.DEFAULT_TABLE_PERPAGE)
const fetchSQL = { const fetchSQL = {
skip: page * perPage, skip: page * perPage,
take: perPage, take: perPage,

View File

@ -4,22 +4,23 @@ import { PrismaService } from 'src/prisma.service'
@Injectable() @Injectable()
export class TodoService { export class TodoService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {
prisma.$on<any>('query', (event: Prisma.QueryEvent) => {
console.log('Query: ' + event.query)
console.log('Duration: ' + event.duration + 'ms')
})
}
//참고: https://intrepidgeeks.com/tutorial/05-instagram-clone-code-5-user-summary //참고: https://intrepidgeeks.com/tutorial/05-instagram-clone-code-5-user-summary
//전체조회 //전체조회
async count(params: { async count(params: {
skip?: number
take?: number
cursor?: Prisma.TodoWhereUniqueInput cursor?: Prisma.TodoWhereUniqueInput
where?: Prisma.TodoWhereInput where?: Prisma.TodoWhereInput
orderBy?: Prisma.TodoOrderByWithRelationInput
}): Promise<number> { }): Promise<number> {
const { skip, take, cursor, where, orderBy } = params const { cursor, where } = params
return this.prisma.todo.count({ return this.prisma.todo.count({
cursor, cursor,
where, where
orderBy
}) })
} }