From 45cc9906f3087ceffd2ca0882c46485faa429851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=86=B7=E1=84=80=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=86=E1=85=B5=E1=86=AB?= Date: Sat, 16 Sep 2023 21:22:14 +0900 Subject: [PATCH 1/7] =?UTF-8?q?=F0=9F=9B=A0=20Refactoring=20Code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - import pg modules --- lib/node-postgres/.env.development.local | 7 + lib/node-postgres/.env.production.local | 7 + lib/node-postgres/.env.test.local | 7 + lib/node-postgres/.swcrc | 1 - lib/node-postgres/src/app.ts | 6 - lib/node-postgres/src/config/index.ts | 2 +- lib/node-postgres/src/database/index.ts | 8 +- lib/node-postgres/src/database/init.sql | 119 ++--------------- .../src/middlewares/auth.middleware.ts | 16 ++- lib/node-postgres/src/models/users.model.ts | 9 -- lib/node-postgres/src/routes/auth.route.ts | 4 +- lib/node-postgres/src/routes/users.route.ts | 4 +- .../src/services/auth.service.ts | 81 +++++++++--- .../src/services/users.service.ts | 124 +++++++++++++++--- lib/node-postgres/src/test/auth.test.ts | 11 +- lib/node-postgres/src/test/users.test.ts | 31 ++--- lib/node-postgres/tsconfig.json | 1 - 17 files changed, 248 insertions(+), 190 deletions(-) delete mode 100644 lib/node-postgres/src/models/users.model.ts diff --git a/lib/node-postgres/.env.development.local b/lib/node-postgres/.env.development.local index dc6fced..0e2aea0 100644 --- a/lib/node-postgres/.env.development.local +++ b/lib/node-postgres/.env.development.local @@ -11,3 +11,10 @@ LOG_DIR = ../logs # CORS ORIGIN = * CREDENTIALS = true + +# DATABASE +POSTGRES_USER = root +POSTGRES_PASSWORD = password +POSTGRES_HOST = localhost +POSTGRES_PORT = 5432 +POSTGRES_DB = dev diff --git a/lib/node-postgres/.env.production.local b/lib/node-postgres/.env.production.local index dad9936..25130f1 100644 --- a/lib/node-postgres/.env.production.local +++ b/lib/node-postgres/.env.production.local @@ -11,3 +11,10 @@ LOG_DIR = ../logs # CORS ORIGIN = your.domain.com CREDENTIALS = true + +# DATABASE +POSTGRES_USER = root +POSTGRES_PASSWORD = password +POSTGRES_HOST = pg +POSTGRES_PORT = 5432 +POSTGRES_DB = dev diff --git a/lib/node-postgres/.env.test.local b/lib/node-postgres/.env.test.local index dc6fced..b0437c1 100644 --- a/lib/node-postgres/.env.test.local +++ b/lib/node-postgres/.env.test.local @@ -11,3 +11,10 @@ LOG_DIR = ../logs # CORS ORIGIN = * CREDENTIALS = true + +# DATABASE +POSTGRES_USER = root +POSTGRES_PASSWORD = password +POSTGRES_HOST = pg +POSTGRES_PORT = 5432 +POSTGRES_DB = dev diff --git a/lib/node-postgres/.swcrc b/lib/node-postgres/.swcrc index 95a2c95..3f93da5 100644 --- a/lib/node-postgres/.swcrc +++ b/lib/node-postgres/.swcrc @@ -28,7 +28,6 @@ "@exceptions/*": ["exceptions/*"], "@interfaces/*": ["interfaces/*"], "@middlewares/*": ["middlewares/*"], - "@models/*": ["models/*"], "@services/*": ["services/*"], "@utils/*": ["utils/*"] } diff --git a/lib/node-postgres/src/app.ts b/lib/node-postgres/src/app.ts index 91e24da..d5c6fc3 100644 --- a/lib/node-postgres/src/app.ts +++ b/lib/node-postgres/src/app.ts @@ -9,7 +9,6 @@ import morgan from 'morgan'; import swaggerJSDoc from 'swagger-jsdoc'; import swaggerUi from 'swagger-ui-express'; import { NODE_ENV, PORT, LOG_FORMAT, ORIGIN, CREDENTIALS } from '@config'; -import { client } from '@database'; import { Routes } from '@interfaces/routes.interface'; import { ErrorMiddleware } from '@middlewares/error.middleware'; import { logger, stream } from '@utils/logger'; @@ -24,7 +23,6 @@ export class App { this.env = NODE_ENV || 'development'; this.port = PORT || 3000; - this.connectToDatabase(); this.initializeMiddlewares(); this.initializeRoutes(routes); this.initializeSwagger(); @@ -44,10 +42,6 @@ export class App { return this.app; } - private async connectToDatabase() { - await client.connect(); - } - private initializeMiddlewares() { this.app.use(morgan(LOG_FORMAT, { stream })); this.app.use(cors({ origin: ORIGIN, credentials: CREDENTIALS })); diff --git a/lib/node-postgres/src/config/index.ts b/lib/node-postgres/src/config/index.ts index 71d0f29..80991e1 100644 --- a/lib/node-postgres/src/config/index.ts +++ b/lib/node-postgres/src/config/index.ts @@ -3,4 +3,4 @@ config({ path: `.env.${process.env.NODE_ENV || 'development'}.local` }); export const CREDENTIALS = process.env.CREDENTIALS === 'true'; export const { NODE_ENV, PORT, SECRET_KEY, LOG_FORMAT, LOG_DIR, ORIGIN } = process.env; -export const { DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_DATABASE } = process.env; +export const { POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB } = process.env; diff --git a/lib/node-postgres/src/database/index.ts b/lib/node-postgres/src/database/index.ts index f76d913..12922e8 100644 --- a/lib/node-postgres/src/database/index.ts +++ b/lib/node-postgres/src/database/index.ts @@ -1,6 +1,10 @@ import { Client } from 'pg'; -import { DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_DATABASE } from '@config'; +import { POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB } from '@config'; export const client = new Client({ - connectionString: `postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_DATABASE}`, + connectionString: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}`, }); + +client.connect(); + +export default client; diff --git a/lib/node-postgres/src/database/init.sql b/lib/node-postgres/src/database/init.sql index f9440c5..79ff110 100644 --- a/lib/node-postgres/src/database/init.sql +++ b/lib/node-postgres/src/database/init.sql @@ -1,110 +1,13 @@ --- TABLE 존재할 경우 삭제 -DROP TABLE IF EXISTS teachers cascade; -DROP TABLE IF EXISTS classes cascade; -DROP TABLE IF EXISTS students cascade; -DROP TABLE IF EXISTS classes_category cascade; -DROP TABLE IF EXISTS enrolment cascade; - --- ============ --- 강사 테이블 --- ============ --- 강사 테이블 생성 -CREATE TABLE teachers( - "teacherId" SERIAL PRIMARY KEY, - -- 강사 ID - "teacherName" VARCHAR(32) NOT NULL, - -- 강사명 - "teacherAbout" VARCHAR(48) -- 강사 정보 -); --- 강사 데이터 생성 -INSERT INTO teachers( - "teacherId", - "teacherName", - "teacherAbout" - ) -VALUES (1, '조현영', '웹 개발 강사'), - (2, '개복치개발자', '안드로이드 코틀린 강사'), - (3, '이고잉', '생활코딩 운영진 겸 강사'), - (4, '김태원', '파이썬 알고리즘 강사'), - (5, '윤재성', 'Kotiln 기반 안드로이드 강사'), - (6, '조훈', '쿠버네티스 강사'), - (7, 'Rookiss', '얼리언 엔진 전문 강사'), - (8, '유용한IT학습', 'SQLD 자격증 취득 강사'), - (9, '김태민', '쿠버네티스 강사'), - (10, '큰돌', '알고리즘 강사'); -SELECT SETVAL( - '"teachers_teacherId_seq"', - ( - SELECT max("teacherId") - FROM teachers - ) - ); --- =================== --- 강의 카테고리 테이블 --- =================== --- 강의 카테고리 테이블 생성 -CREATE TABLE classes_category( - "categoryId" SERIAL PRIMARY KEY, - -- 카테고리 ID - "categoryName" VARCHAR(32) UNIQUE NOT NULL -- 카테고리 명 -); --- 강의 카테고리 데이터 생성 -INSERT INTO classes_category("categoryId", "categoryName") -VALUES (1, '웹'), - (2, '앱'), - (3, '게임'), - (4, '알고리즘'), - (5, '인프라'), - (6, '데이터베이스'); -SELECT SETVAL( - '"classes_category_categoryId_seq"', - ( - SELECT max("categoryId") - FROM classes_category - ) - ); --- ============ --- 강의 테이블 --- ============ --- 강의 테이블 생성 -CREATE TABLE classes( - "classId" SERIAL PRIMARY KEY, - -- 강의 ID - "className" VARCHAR(32) UNIQUE NOT NULL, - -- 강의명 - "classPrice" INTEGER NOT NULL DEFAULT 0, - -- 가격 - "introduce" TEXT, - -- 강의 소개 - "active" BOOLEAN NOT NULL DEFAULT false, - -- 강의 활성화 (true: 공개, false, 비공개) +-- If Exists Table Drop +DROP TABLE IF EXISTS users cascade; +-- ================ +-- TABLE [users] +-- ================ +-- create users table +CREATE TABLE users( + "id" SERIAL PRIMARY KEY, + "email" VARCHAR(32) UNIQUE NOT NULL, + "password" VARCHAR(48) NOT NULL, "createdAt" TIMESTAMP WITHOUT TIME ZONE DEFAULT(NOW() AT TIME ZONE 'utc'), - -- 강의 생성 일자 - "updatedAt" TIMESTAMP WITHOUT TIME ZONE, - -- 강의 수정 일자 - "teacherId" INTEGER REFERENCES teachers("teacherId") ON DELETE CASCADE, - -- 강사 ID - "categoryId" INTEGER REFERENCES classes_category("categoryId") ON DELETE CASCADE -- 강사 ID -); --- ============== --- 수강생 테이블 --- ============== --- 수강생 테이블 생성 -CREATE TABLE students( - "studentId" SERIAL PRIMARY KEY, - -- 수강생 ID - "email" VARCHAR(48) UNIQUE NOT NULL, - -- 수강생 이메일 - "nickname" VARCHAR(32) NOT NULL -- 수강생 닉네임 -); --- =============== --- 수강신청 테이블 --- =============== --- 수강신청 테이블 생성 -CREATE TABLE enrolment( - "classId" INTEGER REFERENCES classes("classId") ON DELETE CASCADE, - -- 강의 ID - "studentId" INTEGER REFERENCES students("studentId") ON DELETE CASCADE, - -- 수강생 ID - "applicationAt" TIMESTAMP WITHOUT TIME ZONE DEFAULT(NOW() AT TIME ZONE 'utc') -- 신청 일자 + "updatedAt" TIMESTAMP WITHOUT TIME ZONE ); \ No newline at end of file diff --git a/lib/node-postgres/src/middlewares/auth.middleware.ts b/lib/node-postgres/src/middlewares/auth.middleware.ts index c311410..9eff334 100644 --- a/lib/node-postgres/src/middlewares/auth.middleware.ts +++ b/lib/node-postgres/src/middlewares/auth.middleware.ts @@ -1,9 +1,9 @@ import { NextFunction, Response } from 'express'; import { verify } from 'jsonwebtoken'; import { SECRET_KEY } from '@config'; +import pg from '@database'; import { HttpException } from '@exceptions/httpException'; import { DataStoredInToken, RequestWithUser } from '@interfaces/auth.interface'; -import { UserModel } from '@models/users.model'; const getAuthorization = req => { const coockie = req.cookies['Authorization']; @@ -21,10 +21,18 @@ export const AuthMiddleware = async (req: RequestWithUser, res: Response, next: if (Authorization) { const { id } = (await verify(Authorization, SECRET_KEY)) as DataStoredInToken; - const findUser = UserModel.find(user => user.id === id); + const { rows, rowCount } = await pg.query(` + SELECT + "email", + "password" + FROM + users + WHERE + "id" = $1 + `, id); - if (findUser) { - req.user = findUser; + if (rowCount) { + req.user = rows[0]; next(); } else { next(new HttpException(401, 'Wrong authentication token')); diff --git a/lib/node-postgres/src/models/users.model.ts b/lib/node-postgres/src/models/users.model.ts deleted file mode 100644 index d5138d8..0000000 --- a/lib/node-postgres/src/models/users.model.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { User } from '@interfaces/users.interface'; - -// password: password -export const UserModel: User[] = [ - { id: 1, email: 'example1@email.com', password: '$2b$10$TBEfaCe1oo.2jfkBDWcj/usBj4oECsW2wOoDXpCa2IH9xqCpEK/hC' }, - { id: 2, email: 'example2@email.com', password: '$2b$10$TBEfaCe1oo.2jfkBDWcj/usBj4oECsW2wOoDXpCa2IH9xqCpEK/hC' }, - { id: 3, email: 'example3@email.com', password: '$2b$10$TBEfaCe1oo.2jfkBDWcj/usBj4oECsW2wOoDXpCa2IH9xqCpEK/hC' }, - { id: 4, email: 'example4@email.com', password: '$2b$10$TBEfaCe1oo.2jfkBDWcj/usBj4oECsW2wOoDXpCa2IH9xqCpEK/hC' }, -]; diff --git a/lib/node-postgres/src/routes/auth.route.ts b/lib/node-postgres/src/routes/auth.route.ts index 1025094..1a18f73 100644 --- a/lib/node-postgres/src/routes/auth.route.ts +++ b/lib/node-postgres/src/routes/auth.route.ts @@ -14,8 +14,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post('/signup', ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post('/login', ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post('/signup', ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post('/login', ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post('/logout', AuthMiddleware, this.auth.logOut); } } diff --git a/lib/node-postgres/src/routes/users.route.ts b/lib/node-postgres/src/routes/users.route.ts index 8f097f5..b750b9f 100644 --- a/lib/node-postgres/src/routes/users.route.ts +++ b/lib/node-postgres/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id(\\d+)`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id(\\d+)`, this.user.deleteUser); } } diff --git a/lib/node-postgres/src/services/auth.service.ts b/lib/node-postgres/src/services/auth.service.ts index ffd0d98..336a0c2 100644 --- a/lib/node-postgres/src/services/auth.service.ts +++ b/lib/node-postgres/src/services/auth.service.ts @@ -2,10 +2,10 @@ import { hash, compare } from 'bcrypt'; import { sign } from 'jsonwebtoken'; import { Service } from 'typedi'; import { SECRET_KEY } from '@config'; +import pg from '@database'; import { HttpException } from '@exceptions/httpException'; import { DataStoredInToken, TokenData } from '@interfaces/auth.interface'; import { User } from '@interfaces/users.interface'; -import { UserModel } from '@models/users.model'; const createToken = (user: User): TokenData => { const dataStoredInToken: DataStoredInToken = { id: user.id }; @@ -21,32 +21,83 @@ const createCookie = (tokenData: TokenData): string => { @Service() export class AuthService { public async signup(userData: User): Promise { - const findUser: User = UserModel.find(user => user.email === userData.email); - if (findUser) throw new HttpException(409, `This email ${userData.email} already exists`); + const { email, password } = userData; - const hashedPassword = await hash(userData.password, 10); - const createUserData: User = { id: UserModel.length + 1, ...userData, password: hashedPassword }; + const { rows: findUser } = await pg.query( + ` + SELECT EXISTS( + SELECT + "email" + FROM + users + WHERE + "email" = $1 + )`, + [email], + ); + if (findUser[0].exists) throw new HttpException(409, `This email ${userData.email} already exists`); - return createUserData; + const hashedPassword = await hash(password, 10); + const { rows: signUpUserData } = await pg.query( + ` + INSERT INTO + users( + "email", + "password" + ) + VALUES ($1, $2) + RETURNING "email", "password" + `, + [email, hashedPassword], + ); + + return signUpUserData[0]; } public async login(userData: User): Promise<{ cookie: string; findUser: User }> { - const findUser: User = UserModel.find(user => user.email === userData.email); - if (!findUser) throw new HttpException(409, `This email ${userData.email} was not found`); + const { email, password } = userData; + + const { rows, rowCount } = await pg.query( + ` + SELECT + "email", + "password" + FROM + users + WHERE + "email" = $1 + `, + [email], + ); + if (!rowCount) throw new HttpException(409, `This email ${email} was not found`); - const isPasswordMatching: boolean = await compare(userData.password, findUser.password); + const isPasswordMatching: boolean = await compare(password, rows[0].password); if (!isPasswordMatching) throw new HttpException(409, "You're password not matching"); - const tokenData = createToken(findUser); + const tokenData = createToken(rows[0]); const cookie = createCookie(tokenData); - - return { cookie, findUser }; + return { cookie, findUser: rows[0] }; } public async logout(userData: User): Promise { - const findUser: User = UserModel.find(user => user.email === userData.email && user.password === userData.password); - if (!findUser) throw new HttpException(409, "User doesn't exist"); + const { email, password } = userData; + + const { rows, rowCount } = await pg.query( + ` + SELECT + "email", + "password" + FROM + users + WHERE + "email" = $1 + AND + "password" = $2 + `, + [email, password], + ); + if (!rowCount) throw new HttpException(409, "User doesn't exist"); - return findUser; + return rows[0]; } } diff --git a/lib/node-postgres/src/services/users.service.ts b/lib/node-postgres/src/services/users.service.ts index 7e3d924..ea3edf4 100644 --- a/lib/node-postgres/src/services/users.service.ts +++ b/lib/node-postgres/src/services/users.service.ts @@ -1,51 +1,133 @@ import { hash } from 'bcrypt'; import { Service } from 'typedi'; +import pg from '@database'; import { HttpException } from '@exceptions/httpException'; import { User } from '@interfaces/users.interface'; -import { UserModel } from '@models/users.model'; @Service() export class UserService { public async findAllUser(): Promise { - const users: User[] = UserModel; - return users; + const { rows } = await pg.query(` + SELECT + * + FROM + users + `); + return rows; } public async findUserById(userId: number): Promise { - const findUser: User = UserModel.find(user => user.id === userId); - if (!findUser) throw new HttpException(409, "User doesn't exist"); + const { rows, rowCount } = await pg.query( + ` + SELECT + * + FROM + users + WHERE + id = $1 + `, + [userId], + ); + if (!rowCount) throw new HttpException(409, "User doesn't exist"); - return findUser; + return rows[0]; } public async createUser(userData: User): Promise { - const findUser: User = UserModel.find(user => user.email === userData.email); - if (findUser) throw new HttpException(409, `This email ${userData.email} already exists`); + const { email, password } = userData; - const hashedPassword = await hash(userData.password, 10); - const createUserData: User = { id: UserModel.length + 1, ...userData, password: hashedPassword }; + const { rows } = await pg.query( + ` + SELECT EXISTS( + SELECT + "email" + FROM + users + WHERE + "email" = $1 + )`, + [email], + ); + if (rows[0].exists) throw new HttpException(409, `This email ${email} already exists`); - return createUserData; + const hashedPassword = await hash(password, 10); + const { rows: createUserData } = await pg.query( + ` + INSERT INTO + users( + "email", + "password" + ) + VALUES ($1, $2) + RETURNING "email", "password" + `, + [email, hashedPassword], + ); + + return createUserData[0]; } public async updateUser(userId: number, userData: User): Promise { - const findUser: User = UserModel.find(user => user.id === userId); - if (!findUser) throw new HttpException(409, "User doesn't exist"); + const { rows: findUser } = await pg.query( + ` + SELECT EXISTS( + SELECT + "id" + FROM + users + WHERE + "id" = $1 + )`, + [userId], + ); + if (findUser[0].exists) throw new HttpException(409, "User doesn't exist"); - const hashedPassword = await hash(userData.password, 10); - const updateUserData: User[] = UserModel.map((user: User) => { - if (user.id === findUser.id) user = { id: userId, ...userData, password: hashedPassword }; - return user; - }); + const { email, password } = userData; + const hashedPassword = await hash(password, 10); + const { rows: updateUserData } = await pg.query( + ` + UPDATE + users + SET + "email" = $2, + "password" = $3 + WHERE + "id" = $1 + RETURNING "email", "password" + `, + [userId, email, hashedPassword], + ); return updateUserData; } public async deleteUser(userId: number): Promise { - const findUser: User = UserModel.find(user => user.id === userId); - if (!findUser) throw new HttpException(409, "User doesn't exist"); + const { rows: findUser } = await pg.query( + ` + SELECT EXISTS( + SELECT + "id" + FROM + users + WHERE + "id" = $1 + )`, + [userId], + ); + if (findUser[0].exists) throw new HttpException(409, "User doesn't exist"); + + const { rows: deleteUserData } = await pg.query( + ` + DELETE + FROM + users + WHERE + id = $1 + RETURNING "email", "password" + `, + [userId], + ); - const deleteUserData: User[] = UserModel.filter(user => user.id !== findUser.id); return deleteUserData; } } diff --git a/lib/node-postgres/src/test/auth.test.ts b/lib/node-postgres/src/test/auth.test.ts index db251a0..3b6a92b 100644 --- a/lib/node-postgres/src/test/auth.test.ts +++ b/lib/node-postgres/src/test/auth.test.ts @@ -1,15 +1,17 @@ import request from 'supertest'; import { App } from '@/app'; +import pg from '@database'; import { CreateUserDto } from '@dtos/users.dto'; import { AuthRoute } from '@routes/auth.route'; afterAll(async () => { await new Promise(resolve => setTimeout(() => resolve(), 500)); + pg.end(); }); describe('Testing Auth', () => { describe('[POST] /signup', () => { - it('response should have the Create userData', () => { + it('response should have the Create userData', async () => { const userData: CreateUserDto = { email: 'example@email.com', password: 'password', @@ -17,7 +19,10 @@ describe('Testing Auth', () => { const authRoute = new AuthRoute(); const app = new App([authRoute]); - return request(app.getServer()).post('/signup').send(userData); + return await request(app.getServer()) + .post('/signup') + .send(userData) + .expect(201); }); }); @@ -31,7 +36,7 @@ describe('Testing Auth', () => { const authRoute = new AuthRoute(); const app = new App([authRoute]); - return request(app.getServer()) + return await request(app.getServer()) .post('/login') .send(userData) .expect('Set-Cookie', /^Authorization=.+/); diff --git a/lib/node-postgres/src/test/users.test.ts b/lib/node-postgres/src/test/users.test.ts index cf6ac8e..ec03422 100644 --- a/lib/node-postgres/src/test/users.test.ts +++ b/lib/node-postgres/src/test/users.test.ts @@ -1,33 +1,35 @@ import request from 'supertest'; -import App from '@/app'; +import { App } from '@/app'; +import pg from '@database'; import { CreateUserDto } from '@dtos/users.dto'; -import { User } from '@interfaces/users.interface'; -import { UserModel } from '@models/users.model'; import { UserRoute } from '@routes/users.route'; afterAll(async () => { await new Promise(resolve => setTimeout(() => resolve(), 500)); + pg.end(); }); describe('Testing Users', () => { describe('[GET] /users', () => { - it('response statusCode 200 / findAll', () => { - const findUser: User[] = UserModel; + it('response statusCode 200 / findAll', async () => { const usersRoute = new UserRoute(); const app = new App([usersRoute]); - return request(app.getServer()).get(`${usersRoute.path}`).expect(200, { data: findUser, message: 'findAll' }); + return await request(app.getServer()).get(`${usersRoute.path}`).expect(200); }); }); describe('[GET] /users/:id', () => { - it('response statusCode 200 / findOne', () => { - const userId = 1; - const findUser: User = UserModel.find(user => user.id === userId); + it('response statusCode 200 / findOne', async () => { const usersRoute = new UserRoute(); const app = new App([usersRoute]); - return request(app.getServer()).get(`${usersRoute.path}/${userId}`).expect(200, { data: findUser, message: 'findOne' }); + return await request(app.getServer()) + .get(`${usersRoute.path}`) + .query({ + userId: 1, + }) + .expect(200); }); }); @@ -40,7 +42,7 @@ describe('Testing Users', () => { const usersRoute = new UserRoute(); const app = new App([usersRoute]); - return request(app.getServer()).post(`${usersRoute.path}`).send(userData).expect(201); + return await request(app.getServer()).post(`${usersRoute.path}`).send(userData).expect(201); }); }); @@ -54,18 +56,17 @@ describe('Testing Users', () => { const usersRoute = new UserRoute(); const app = new App([usersRoute]); - return request(app.getServer()).put(`${usersRoute.path}/${userId}`).send(userData).expect(200); + return await request(app.getServer()).put(`${usersRoute.path}/${userId}`).send(userData).expect(200); }); }); describe('[DELETE] /users/:id', () => { - it('response statusCode 200 / deleted', () => { + it('response statusCode 200 / deleted', async () => { const userId = 1; - const deleteUser: User[] = UserModel.filter(user => user.id !== userId); const usersRoute = new UserRoute(); const app = new App([usersRoute]); - return request(app.getServer()).delete(`${usersRoute.path}/${userId}`).expect(200, { data: deleteUser, message: 'deleted' }); + return await request(app.getServer()).delete(`${usersRoute.path}/${userId}`).expect(200); }); }); }); diff --git a/lib/node-postgres/tsconfig.json b/lib/node-postgres/tsconfig.json index 937ff08..c1224b3 100644 --- a/lib/node-postgres/tsconfig.json +++ b/lib/node-postgres/tsconfig.json @@ -29,7 +29,6 @@ "@exceptions/*": ["exceptions/*"], "@interfaces/*": ["interfaces/*"], "@middlewares/*": ["middlewares/*"], - "@models/*": ["models/*"], "@routes/*": ["routes/*"], "@services/*": ["services/*"], "@utils/*": ["utils/*"] From 620e81f30779b970baa11daf6851068ccc7086f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=86=B7=E1=84=80=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=86=E1=85=B5=E1=86=AB?= Date: Sat, 16 Sep 2023 21:23:52 +0900 Subject: [PATCH 2/7] =?UTF-8?q?=F0=9F=90=9E=20Fix=20Bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pg container, an error occurs that the environment key - #218 --- lib/typeorm/.env.development.local | 10 +++++----- lib/typeorm/.env.production.local | 10 +++++----- lib/typeorm/.env.test.local | 10 +++++----- lib/typeorm/docker-compose.yml | 16 ++++++++-------- lib/typeorm/src/config/index.ts | 2 +- lib/typeorm/src/database/index.ts | 12 ++++++------ 6 files changed, 30 insertions(+), 30 deletions(-) diff --git a/lib/typeorm/.env.development.local b/lib/typeorm/.env.development.local index 1307310..175c08c 100644 --- a/lib/typeorm/.env.development.local +++ b/lib/typeorm/.env.development.local @@ -2,11 +2,11 @@ PORT = 3000 # DATABASE -DB_USER = root -DB_PASSWORD = password -DB_HOST = localhost -DB_PORT = 5432 -DB_DATABASE = dev +POSTGRES_USER = root +POSTGRES_PASSWORD = password +POSTGRES_HOST = localhost +POSTGRES_PORT = 5432 +POSTGRES_DATABASE = dev # TOKEN SECRET_KEY = secretKey diff --git a/lib/typeorm/.env.production.local b/lib/typeorm/.env.production.local index aa8022c..cc10459 100644 --- a/lib/typeorm/.env.production.local +++ b/lib/typeorm/.env.production.local @@ -2,11 +2,11 @@ PORT = 3000 # DATABASE -DB_USER = root -DB_PASSWORD = password -DB_HOST = localhost -DB_PORT = 5432 -DB_DATABASE = dev +POSTGRES_USER = root +POSTGRES_PASSWORD = password +POSTGRES_HOST = localhost +POSTGRES_PORT = 5432 +POSTGRES_DATABASE = dev # TOKEN SECRET_KEY = secretKey diff --git a/lib/typeorm/.env.test.local b/lib/typeorm/.env.test.local index 1307310..175c08c 100644 --- a/lib/typeorm/.env.test.local +++ b/lib/typeorm/.env.test.local @@ -2,11 +2,11 @@ PORT = 3000 # DATABASE -DB_USER = root -DB_PASSWORD = password -DB_HOST = localhost -DB_PORT = 5432 -DB_DATABASE = dev +POSTGRES_USER = root +POSTGRES_PASSWORD = password +POSTGRES_HOST = localhost +POSTGRES_PORT = 5432 +POSTGRES_DATABASE = dev # TOKEN SECRET_KEY = secretKey diff --git a/lib/typeorm/docker-compose.yml b/lib/typeorm/docker-compose.yml index 70e2311..74acd93 100644 --- a/lib/typeorm/docker-compose.yml +++ b/lib/typeorm/docker-compose.yml @@ -20,11 +20,11 @@ services: ports: - "3000:3000" environment: - DB_USER: root - DB_PASSWORD: password - DB_HOST: pg - DB_PORT: 5432 - DB_DATABASE: dev + POSTGRES_USER: root + POSTGRES_PASSWORD: password + POSTGRES_HOST: pg + POSTGRES_PORT: 5432 + POSTGRES_DATABASE: dev volumes: - ./:/app - /app/node_modules @@ -40,9 +40,9 @@ services: container_name: pg image: postgres:14.5-alpine environment: - DB_USER: root - DB_PASSWORD: password - DB_DATABASE: dev + POSTGRES_USER: root + POSTGRES_PASSWORD: password + POSTGRES_DB: dev ports: - "5432:5432" networks: diff --git a/lib/typeorm/src/config/index.ts b/lib/typeorm/src/config/index.ts index 71d0f29..8dae560 100644 --- a/lib/typeorm/src/config/index.ts +++ b/lib/typeorm/src/config/index.ts @@ -3,4 +3,4 @@ config({ path: `.env.${process.env.NODE_ENV || 'development'}.local` }); export const CREDENTIALS = process.env.CREDENTIALS === 'true'; export const { NODE_ENV, PORT, SECRET_KEY, LOG_FORMAT, LOG_DIR, ORIGIN } = process.env; -export const { DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_DATABASE } = process.env; +export const { POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DATABASE } = process.env; diff --git a/lib/typeorm/src/database/index.ts b/lib/typeorm/src/database/index.ts index a92ce87..f9e9ac4 100644 --- a/lib/typeorm/src/database/index.ts +++ b/lib/typeorm/src/database/index.ts @@ -1,15 +1,15 @@ import { join } from 'path'; import { createConnection, ConnectionOptions } from 'typeorm'; -import { DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_DATABASE } from '@config'; +import { POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DATABASE } from '@config'; export const dbConnection = async () => { const dbConfig: ConnectionOptions = { type: 'postgres', - username: DB_USER, - password: DB_PASSWORD, - host: DB_HOST, - port: Number(DB_PORT), - database: DB_DATABASE, + username: POSTGRES_USER, + password: POSTGRES_PASSWORD, + host: POSTGRES_HOST, + port: +POSTGRES_PORT, + database: POSTGRES_DATABASE, synchronize: true, logging: false, entities: [join(__dirname, '../**/*.entity{.ts,.js}')], From 73698413ec2a0dab3bf47ac1052db7075cbca78c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=86=B7=E1=84=80=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=86=E1=85=B5=E1=86=AB?= Date: Sat, 16 Sep 2023 21:25:36 +0900 Subject: [PATCH 3/7] =?UTF-8?q?=F0=9F=8C=BC=20Update=20Version=20-=20v10.1?= =?UTF-8?q?.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 632be1e..b863807 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "typescript-express-starter", - "version": "10.0.1", + "version": "10.1.1", "description": "Quick and Easy TypeScript Express Starter", "author": "AGUMON ", "license": "MIT", From 2839d6c18314d0b3e6f00b56ec464349863775a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=86=B7=E1=84=80=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=86=E1=85=B5=E1=86=AB?= Date: Wed, 4 Oct 2023 19:38:46 +0900 Subject: [PATCH 4/7] =?UTF-8?q?=F0=9F=9B=A0=20Refactoring=20Code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix ValidationMiddleware Parameter --- lib/mikro-orm/src/routes/auth.route.ts | 4 ++-- lib/mikro-orm/src/routes/users.route.ts | 4 ++-- lib/mongoose/src/routes/auth.route.ts | 4 ++-- lib/mongoose/src/routes/users.route.ts | 4 ++-- lib/prisma/src/routes/auth.route.ts | 4 ++-- lib/prisma/src/routes/users.route.ts | 4 ++-- lib/routing-controllers/package.json | 2 +- lib/routing-controllers/src/controllers/auth.controller.ts | 4 ++-- lib/routing-controllers/src/controllers/users.controller.ts | 4 ++-- lib/sequelize/src/routes/auth.route.ts | 4 ++-- lib/sequelize/src/routes/users.route.ts | 4 ++-- lib/typegoose/src/routes/auth.route.ts | 4 ++-- lib/typegoose/src/routes/users.route.ts | 4 ++-- lib/typeorm/src/routes/auth.route.ts | 4 ++-- lib/typeorm/src/routes/users.route.ts | 4 ++-- 15 files changed, 29 insertions(+), 29 deletions(-) diff --git a/lib/mikro-orm/src/routes/auth.route.ts b/lib/mikro-orm/src/routes/auth.route.ts index 118af5e..a32969f 100644 --- a/lib/mikro-orm/src/routes/auth.route.ts +++ b/lib/mikro-orm/src/routes/auth.route.ts @@ -15,8 +15,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post(`${this.path}signup`, ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post(`${this.path}login`, ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post(`${this.path}signup`, ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post(`${this.path}login`, ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post(`${this.path}logout`, AuthMiddleware, this.auth.logOut); } } diff --git a/lib/mikro-orm/src/routes/users.route.ts b/lib/mikro-orm/src/routes/users.route.ts index c56a39b..957f192 100644 --- a/lib/mikro-orm/src/routes/users.route.ts +++ b/lib/mikro-orm/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id`, this.user.deleteUser); } } diff --git a/lib/mongoose/src/routes/auth.route.ts b/lib/mongoose/src/routes/auth.route.ts index 118af5e..a32969f 100644 --- a/lib/mongoose/src/routes/auth.route.ts +++ b/lib/mongoose/src/routes/auth.route.ts @@ -15,8 +15,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post(`${this.path}signup`, ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post(`${this.path}login`, ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post(`${this.path}signup`, ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post(`${this.path}login`, ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post(`${this.path}logout`, AuthMiddleware, this.auth.logOut); } } diff --git a/lib/mongoose/src/routes/users.route.ts b/lib/mongoose/src/routes/users.route.ts index c56a39b..957f192 100644 --- a/lib/mongoose/src/routes/users.route.ts +++ b/lib/mongoose/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id`, this.user.deleteUser); } } diff --git a/lib/prisma/src/routes/auth.route.ts b/lib/prisma/src/routes/auth.route.ts index 118af5e..a32969f 100644 --- a/lib/prisma/src/routes/auth.route.ts +++ b/lib/prisma/src/routes/auth.route.ts @@ -15,8 +15,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post(`${this.path}signup`, ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post(`${this.path}login`, ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post(`${this.path}signup`, ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post(`${this.path}login`, ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post(`${this.path}logout`, AuthMiddleware, this.auth.logOut); } } diff --git a/lib/prisma/src/routes/users.route.ts b/lib/prisma/src/routes/users.route.ts index 8f097f5..b750b9f 100644 --- a/lib/prisma/src/routes/users.route.ts +++ b/lib/prisma/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id(\\d+)`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id(\\d+)`, this.user.deleteUser); } } diff --git a/lib/routing-controllers/package.json b/lib/routing-controllers/package.json index cbdb85d..b066800 100644 --- a/lib/routing-controllers/package.json +++ b/lib/routing-controllers/package.json @@ -10,7 +10,7 @@ "build": "swc src -d dist --source-maps --copy-files", "build:tsc": "tsc && tsc-alias", "test": "jest --forceExit --detectOpenHandles", - "lint": "eslint --ignore-path .gitignore --ext .ts src/", + "lint": "eslint --ignore-path .gitignore --ext .ts src", "lint:fix": "npm run lint -- --fix", "deploy:prod": "npm run build && pm2 start ecosystem.config.js --only prod", "deploy:dev": "pm2 start ecosystem.config.js --only dev" diff --git a/lib/routing-controllers/src/controllers/auth.controller.ts b/lib/routing-controllers/src/controllers/auth.controller.ts index bd4133e..7bac911 100644 --- a/lib/routing-controllers/src/controllers/auth.controller.ts +++ b/lib/routing-controllers/src/controllers/auth.controller.ts @@ -13,7 +13,7 @@ export class AuthController { public auth = Container.get(AuthService); @Post('/signup') - @UseBefore(ValidationMiddleware(CreateUserDto, 'body')) + @UseBefore(ValidationMiddleware(CreateUserDto)) @HttpCode(201) async signUp(@Body() userData: User) { const signUpUserData: User = await this.auth.signup(userData); @@ -21,7 +21,7 @@ export class AuthController { } @Post('/login') - @UseBefore(ValidationMiddleware(CreateUserDto, 'body')) + @UseBefore(ValidationMiddleware(CreateUserDto)) async logIn(@Res() res: Response, @Body() userData: User) { const { cookie, findUser } = await this.auth.login(userData); diff --git a/lib/routing-controllers/src/controllers/users.controller.ts b/lib/routing-controllers/src/controllers/users.controller.ts index 4a9ce7a..8a7084f 100644 --- a/lib/routing-controllers/src/controllers/users.controller.ts +++ b/lib/routing-controllers/src/controllers/users.controller.ts @@ -27,7 +27,7 @@ export class UserController { @Post('/users') @HttpCode(201) - @UseBefore(ValidationMiddleware(CreateUserDto, 'body')) + @UseBefore(ValidationMiddleware(CreateUserDto)) @OpenAPI({ summary: 'Create a new user' }) async createUser(@Body() userData: User) { const createUserData: User = await this.user.createUser(userData); @@ -35,7 +35,7 @@ export class UserController { } @Put('/users/:id') - @UseBefore(ValidationMiddleware(CreateUserDto, 'body', true)) + @UseBefore(ValidationMiddleware(CreateUserDto, true)) @OpenAPI({ summary: 'Update a user' }) async updateUser(@Param('id') userId: number, @Body() userData: User) { const updateUserData: User[] = await this.user.updateUser(userId, userData); diff --git a/lib/sequelize/src/routes/auth.route.ts b/lib/sequelize/src/routes/auth.route.ts index 1025094..1a18f73 100644 --- a/lib/sequelize/src/routes/auth.route.ts +++ b/lib/sequelize/src/routes/auth.route.ts @@ -14,8 +14,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post('/signup', ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post('/login', ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post('/signup', ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post('/login', ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post('/logout', AuthMiddleware, this.auth.logOut); } } diff --git a/lib/sequelize/src/routes/users.route.ts b/lib/sequelize/src/routes/users.route.ts index 8f097f5..b750b9f 100644 --- a/lib/sequelize/src/routes/users.route.ts +++ b/lib/sequelize/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id(\\d+)`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id(\\d+)`, this.user.deleteUser); } } diff --git a/lib/typegoose/src/routes/auth.route.ts b/lib/typegoose/src/routes/auth.route.ts index 1025094..1a18f73 100644 --- a/lib/typegoose/src/routes/auth.route.ts +++ b/lib/typegoose/src/routes/auth.route.ts @@ -14,8 +14,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post('/signup', ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post('/login', ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post('/signup', ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post('/login', ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post('/logout', AuthMiddleware, this.auth.logOut); } } diff --git a/lib/typegoose/src/routes/users.route.ts b/lib/typegoose/src/routes/users.route.ts index c56a39b..957f192 100644 --- a/lib/typegoose/src/routes/users.route.ts +++ b/lib/typegoose/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id`, this.user.deleteUser); } } diff --git a/lib/typeorm/src/routes/auth.route.ts b/lib/typeorm/src/routes/auth.route.ts index 1025094..1a18f73 100644 --- a/lib/typeorm/src/routes/auth.route.ts +++ b/lib/typeorm/src/routes/auth.route.ts @@ -14,8 +14,8 @@ export class AuthRoute implements Routes { } private initializeRoutes() { - this.router.post('/signup', ValidationMiddleware(CreateUserDto, 'body'), this.auth.signUp); - this.router.post('/login', ValidationMiddleware(CreateUserDto, 'body'), this.auth.logIn); + this.router.post('/signup', ValidationMiddleware(CreateUserDto), this.auth.signUp); + this.router.post('/login', ValidationMiddleware(CreateUserDto), this.auth.logIn); this.router.post('/logout', AuthMiddleware, this.auth.logOut); } } diff --git a/lib/typeorm/src/routes/users.route.ts b/lib/typeorm/src/routes/users.route.ts index 8f097f5..b750b9f 100644 --- a/lib/typeorm/src/routes/users.route.ts +++ b/lib/typeorm/src/routes/users.route.ts @@ -16,8 +16,8 @@ export class UserRoute implements Routes { private initializeRoutes() { this.router.get(`${this.path}`, this.user.getUsers); this.router.get(`${this.path}/:id(\\d+)`, this.user.getUserById); - this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto, 'body'), this.user.createUser); - this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, 'body', true), this.user.updateUser); + this.router.post(`${this.path}`, ValidationMiddleware(CreateUserDto), this.user.createUser); + this.router.put(`${this.path}/:id(\\d+)`, ValidationMiddleware(CreateUserDto, true), this.user.updateUser); this.router.delete(`${this.path}/:id(\\d+)`, this.user.deleteUser); } } From 042fc6a9ea562a081a7404c4e648cc415eb36a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=86=B7=E1=84=80=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=86=E1=85=B5=E1=86=AB?= Date: Wed, 4 Oct 2023 19:39:31 +0900 Subject: [PATCH 5/7] =?UTF-8?q?=F0=9F=8C=BC=20Update=20Version=20-=20v10.2?= =?UTF-8?q?.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b863807..11fa391 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "typescript-express-starter", - "version": "10.1.1", + "version": "10.2.1", "description": "Quick and Easy TypeScript Express Starter", "author": "AGUMON ", "license": "MIT", From f8fa62d4a75477f9f3d7c1f3d9878b9484c437b8 Mon Sep 17 00:00:00 2001 From: Royce Date: Tue, 27 Feb 2024 23:35:51 +0800 Subject: [PATCH 6/7] Fix missing client config error --- lib/knex/knexfile.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/knex/knexfile.ts b/lib/knex/knexfile.ts index 0fcc850..f56bba2 100644 --- a/lib/knex/knexfile.ts +++ b/lib/knex/knexfile.ts @@ -1,6 +1,6 @@ import { DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_DATABASE } from './src/config'; -export const dbConfig = { +const dbConfig = { client: 'mysql', connection: { charset: 'utf8', @@ -21,3 +21,5 @@ export const dbConfig = { // stub: 'src/database/stubs', }, }; + +export default dbConfig From 1e400c12e689f767dc6774f64bf60b758b32dbb0 Mon Sep 17 00:00:00 2001 From: Royce Date: Tue, 27 Feb 2024 23:36:24 +0800 Subject: [PATCH 7/7] Fix invalid migration must have both an up and down function --- lib/knex/src/database/migrations/20210713110926_initial.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/knex/src/database/migrations/20210713110926_initial.ts b/lib/knex/src/database/migrations/20210713110926_initial.ts index 708027b..8f96748 100644 --- a/lib/knex/src/database/migrations/20210713110926_initial.ts +++ b/lib/knex/src/database/migrations/20210713110926_initial.ts @@ -1,6 +1,6 @@ import { Knex } from 'knex'; -const up = (knex: Knex): Promise => { +export const up = (knex: Knex): Promise => { return knex.schema.createTable('users', table => { table.bigIncrements('id').unsigned().primary(); table.string('email', 45).notNullable(); @@ -10,8 +10,6 @@ const up = (knex: Knex): Promise => { }); }; -const down = (knex: Knex): Promise => { +export const down = (knex: Knex): Promise => { return knex.schema.dropTable('users'); }; - -export default { up, down };