Skip to content

Commit

Permalink
Merge pull request #52 from ljlm0402/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
ljlm0402 authored Dec 4, 2020
2 parents ca6cc6a + 93d29f1 commit 109cbb3
Show file tree
Hide file tree
Showing 18 changed files with 134 additions and 69 deletions.
2 changes: 1 addition & 1 deletion lib/default/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class App {
constructor(routes: Routes[]) {
this.app = express();
this.port = process.env.PORT || 3000;
this.env = process.env.NODE_ENV || 'production';
this.env = process.env.NODE_ENV || 'development';

this.initializeMiddlewares();
this.initializeRoutes(routes);
Expand Down
2 changes: 1 addition & 1 deletion lib/mongoose/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class App {
constructor(routes: Routes[]) {
this.app = express();
this.port = process.env.PORT || 3000;
this.env = process.env.NODE_ENV || 'production';
this.env = process.env.NODE_ENV || 'development';

this.connectToDatabase();
this.initializeMiddlewares();
Expand Down
7 changes: 3 additions & 4 deletions lib/sequelize/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import 'reflect-metadata';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
Expand All @@ -8,7 +7,7 @@ import morgan from 'morgan';
import compression from 'compression';
import swaggerUi from 'swagger-ui-express';
import swaggerJSDoc from 'swagger-jsdoc';
import sequelize from './database';
import DB from './database';
import Routes from './interfaces/routes.interface';
import errorMiddleware from './middlewares/error.middleware';
import { logger, stream } from './utils/logger';
Expand All @@ -21,7 +20,7 @@ class App {
constructor(routes: Routes[]) {
this.app = express();
this.port = process.env.PORT || 3000;
this.env = process.env.NODE_ENV || 'production';
this.env = process.env.NODE_ENV || 'development';

this.connectToDatabase();
this.initializeMiddlewares();
Expand All @@ -41,7 +40,7 @@ class App {
}

private connectToDatabase() {
sequelize.sync({ force: false });
DB.sequelize.sync({ force: false });
}

private initializeMiddlewares() {
Expand Down
25 changes: 25 additions & 0 deletions lib/sequelize/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const dbConfig = {
development: {
username: 'root',
password: 'password',
database: 'sequelize',
host: 'localhost',
dialect: 'mysql',
},
test: {
username: 'root',
password: 'password',
database: 'sequelize',
host: 'localhost',
dialect: 'mysql',
},
production: {
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
host: process.env.MYSQL_HOST,
dialect: 'mysql',
},
};

export default dbConfig;
35 changes: 21 additions & 14 deletions lib/sequelize/src/database/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
import { Sequelize } from 'sequelize-typescript';
import User from '../models/users.model';
import Sequelize from 'sequelize';
import config from '../config';
import { logger } from '../utils/logger';
import UserModel from '../models/users.model';

const { MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST } = process.env;
const sequelize = new Sequelize(MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD, {
host: MYSQL_HOST,
dialect: 'mysql',
const env = process.env.NODE_ENV || 'development';
const sequelize = new Sequelize.Sequelize(config[env].database, config[env].username, config[env].password, {
host: config[env].host,
dialect: config[env].dialect,
timezone: '+09:00',
define: {
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
underscored: true,
freezeTableName: true,
},
pool: {
min: 0,
max: 30,
idle: 10000,
acquire: 30000,
pool: config[env].pool,
logQueryParameters: env === 'development',
logging: (query, time) => {
logger.info(time + 'ms' + ' ' + query);
},
benchmark: true,
});

sequelize.addModels([User]);

sequelize
.authenticate()
.then(() => {
Expand All @@ -30,4 +31,10 @@ sequelize
logger.error(`🔴 Unable to connect to the database: ${error}.`);
});

export default sequelize;
const DB = {
Users: UserModel(sequelize),
sequelize, // connection instance (RAW queries)
Sequelize, // library
};

export default DB;
6 changes: 3 additions & 3 deletions lib/sequelize/src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import { NextFunction, Response } from 'express';
import jwt from 'jsonwebtoken';
import HttpException from '../exceptions/HttpException';
import { DataStoredInToken, RequestWithUser } from '../interfaces/auth.interface';
import userModel from '../models/users.model';
import DB from '../database';

const authMiddleware = async (req: RequestWithUser, res: Response, next: NextFunction) => {
try {
const cookies = req.cookies;

if (cookies && cookies.Authorization) {
const secret = process.env.JWT_SECRET;
const verificationResponse = (await jwt.verify(cookies.Authorization, secret)) as DataStoredInToken;
const verificationResponse = jwt.verify(cookies.Authorization, secret) as DataStoredInToken;
const userId = verificationResponse.id;
const findUser = await userModel.findByPk(userId);
const findUser = await DB.Users.findByPk(userId);

if (findUser) {
req.user = findUser;
Expand Down
Empty file.
48 changes: 35 additions & 13 deletions lib/sequelize/src/models/users.model.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
import { AllowNull, AutoIncrement, Column, DataType, Model, PrimaryKey, Table } from 'sequelize-typescript';
import { Sequelize, DataTypes, Model, Optional } from 'sequelize';
import { User } from '../interfaces/users.interface';

@Table({ modelName: 'user', timestamps: true, paranoid: true })
export default class User extends Model<User> {
@PrimaryKey
@AutoIncrement
@Column
id: number;
export type UserCreationAttributes = Optional<User, 'id' | 'email' | 'password'>;

@AllowNull(false)
@Column(DataType.STRING(45))
email: string;
export class UserModel extends Model<User, UserCreationAttributes> implements User {
public id: number;
public email: string;
public password: string;

@AllowNull(false)
@Column(DataType.STRING(255))
password: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}

export default function (sequelize: Sequelize): typeof UserModel {
UserModel.init(
{
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
email: {
allowNull: false,
type: DataTypes.STRING(45),
},
password: {
allowNull: false,
type: DataTypes.STRING(255),
},
},
{
tableName: 'users',
sequelize,
},
);

return UserModel;
}
3 changes: 1 addition & 2 deletions lib/sequelize/src/routes/index.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import IndexController from '../controllers/index.controller';
import Route from '../interfaces/routes.interface';

class IndexRoute implements Route {
public path = '/';
public router = Router();
public indexController = new IndexController();

Expand All @@ -12,7 +11,7 @@ class IndexRoute implements Route {
}

private initializeRoutes() {
this.router.get(`${this.path}`, this.indexController.index);
this.router.get('/', this.indexController.index);
}
}

Expand Down
Empty file.
4 changes: 2 additions & 2 deletions lib/sequelize/src/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { CreateUserDto } from '../dtos/users.dto';
import HttpException from '../exceptions/HttpException';
import { DataStoredInToken, TokenData } from '../interfaces/auth.interface';
import { User } from '../interfaces/users.interface';
import userModel from '../models/users.model';
import DB from '../database';
import { isEmpty } from '../utils/util';

class AuthService {
public users = userModel;
public users = DB.Users;

public async signup(userData: CreateUserDto): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
Expand Down
27 changes: 18 additions & 9 deletions lib/sequelize/src/services/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@ import bcrypt from 'bcrypt';
import { CreateUserDto } from '../dtos/users.dto';
import HttpException from '../exceptions/HttpException';
import { User } from '../interfaces/users.interface';
import userModel from '../models/users.model';
import DB from '../database';
import { isEmpty } from '../utils/util';

class UserService {
public users = userModel;
public users = DB.Users;

public async findAllUser(): Promise<User[]> {
const users: User[] = await this.users.findAll();
return users;
const allUser: User[] = await this.users.findAll();
return allUser;
}

public async findUserById(userId: number): Promise<User> {
if (isEmpty(userId)) throw new HttpException(400, "You're not userId");

const findUser: User = await this.users.findByPk(userId);
if (!findUser) throw new HttpException(409, "You're not user");

Expand All @@ -35,18 +37,25 @@ class UserService {
public async updateUser(userId: number, userData: User): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "You're not userData");

const findUser: User = await this.users.findByPk(userId);
if (!findUser) throw new HttpException(409, "You're not user");

const hashedPassword = await bcrypt.hash(userData.password, 10);
const updateUser: User = await this.users.update({ ...userData, password: hashedPassword }, { where: { id: userId } });
if (!updateUser) throw new HttpException(409, "You're not user");
await this.users.update({ ...userData, password: hashedPassword }, { where: { id: userId } });

const updateUser: User = await this.users.findByPk(userId);
return updateUser;
}

public async deleteUserData(userId: number): Promise<User> {
const deleteUser: User = await this.users.destroy({ where: { id: userId } });
if (!deleteUser) throw new HttpException(409, "You're not user");
if (isEmpty(userId)) throw new HttpException(400, "You're not userId");

return deleteUser;
const findUser: User = await this.users.findByPk(userId);
if (!findUser) throw new HttpException(409, "You're not user");

await this.users.destroy({ where: { id: userId } });

return findUser;
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/sequelize/src/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe('Testing Index', () => {
const indexRoute = new IndexRoute();
const app = new App([indexRoute]);

return request(app.getServer()).get(`${indexRoute.path}`).expect(200);
return request(app.getServer()).get('/').expect(200);
});
});
});
18 changes: 9 additions & 9 deletions lib/sequelize/src/tests/users.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import request from 'supertest';
import App from '../app';
import { User } from '../interfaces/users.interface';
import userModel from '../models/users.model';
import DB from '../database';
import UserRoute from '../routes/users.route';
import { CreateUserDto } from '../dtos/users.dto';

Expand All @@ -11,21 +11,21 @@ afterAll(async () => {

describe('Testing Users', () => {
describe('[GET] /users', () => {
it('response statusCode 200 / findAll', () => {
const findUser: User[] = userModel.findAll();
it('response statusCode 200 / findAll', async () => {
const usersRoute = new UserRoute();
const app = new App([usersRoute]);
const allUser: User[] = await DB.Users.findAll();

return request(app.getServer()).get(`${usersRoute.path}`).expect(200, { data: findUser, message: 'findAll' });
return request(app.getServer()).get(`${usersRoute.path}`).expect(200, { data: allUser, message: 'findAll' });
});
});

describe('[GET] /users/:id', () => {
it('response statusCode 200 / findOne', () => {
const userId = 1;
const findUser: User = userModel.findByPk(userId);
it('response statusCode 200 / findOne', async () => {
const usersRoute = new UserRoute();
const app = new App([usersRoute]);
const userId = 1;
const findUser: User = await DB.Users.findByPk(userId);

return request(app.getServer()).get(`${usersRoute.path}/${userId}`).expect(200, { data: findUser, message: 'findOne' });
});
Expand Down Expand Up @@ -59,9 +59,9 @@ describe('Testing Users', () => {
});

describe('[DELETE] /users/:id', () => {
it('response statusCode 200 / deleted', () => {
it('response statusCode 200 / deleted', async () => {
const userId = 1;
const deleteUser: User = userModel.destroy({ where: { id: userId } });
const deleteUser = await DB.Users.destroy({ where: { id: userId } });
const usersRoute = new UserRoute();
const app = new App([usersRoute]);

Expand Down
9 changes: 5 additions & 4 deletions lib/starter.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,15 @@ async function updatePackageJson(destination) {

async function getDependencies(directory) {
switch (directory) {
case 'mongoose': {
case 'mongoose': { // MongoDB
npm.save += ' mongoose';
npm.dev += ' @types/mongoose';
} break;
case 'sequelize': {
npm.save += ' mysql2 sequelize@^5.22.2 sequelize-typescript reflect-metadata';
case 'sequelize': { // MySQL
npm.save += ' mysql2 sequelize';
npm.dev += ' @types/sequelize sequelize-cli';
} break;
case 'typeorm': {
case 'typeorm': { // PostgreSQL
npm.save += ' pg typeorm reflect-metadata';
} break;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/typeorm/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class App {
constructor(routes: Routes[]) {
this.app = express();
this.port = process.env.PORT || 3000;
this.env = process.env.NODE_ENV || 'production';
this.env = process.env.NODE_ENV || 'development';

this.connectToDatabase();
this.initializeMiddlewares();
Expand Down
Loading

0 comments on commit 109cbb3

Please sign in to comment.