From 0fd9ae15980b2ca1312b8b2f410bdd6015452793 Mon Sep 17 00:00:00 2001 From: _david Date: Sun, 9 Feb 2025 17:21:57 +0700 Subject: [PATCH] update mongo db and test --- src/__tests__/database/mongo.db.ts | 40 ++++++++++++++++++++++++++++++ src/database/mongo.db.ts | 24 ++++++++---------- src/server.ts | 16 +++++++++--- src/utils/bcrypt.ts | 5 ++-- 4 files changed, 66 insertions(+), 19 deletions(-) create mode 100644 src/__tests__/database/mongo.db.ts diff --git a/src/__tests__/database/mongo.db.ts b/src/__tests__/database/mongo.db.ts new file mode 100644 index 0000000..ca60aaf --- /dev/null +++ b/src/__tests__/database/mongo.db.ts @@ -0,0 +1,40 @@ +import mongoose from 'mongoose'; +import connectMongo from '@/database/mongo.db'; +import { _log } from '@/utils'; + +jest.mock('mongoose', () => ({ + connect: jest.fn(), +})); + +jest.mock('@/utils', () => ({ + _log: jest.fn(), +})); + +describe('connectMongo', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should return true and log "MongoDB Connected!" when successful', async () => { + (mongoose.connect as jest.Mock).mockResolvedValueOnce(undefined); + + const result = await connectMongo(); + + expect(result).toBe(true); + expect(mongoose.connect).toHaveBeenCalled(); + expect(_log).toHaveBeenCalledWith('MongoDB Connected!'); + }); + + it('should return false and log error when connection fails', async () => { + const errorMessage = new Error('Connection failed'); + (mongoose.connect as jest.Mock).mockRejectedValueOnce(errorMessage); + + const result = await connectMongo(); + + expect(result).toBe(false); + expect(_log).toHaveBeenCalledWith({ + text: `MongoDB Connect failed !!! ${errorMessage}`, + type: 'error', + }); + }); +}); \ No newline at end of file diff --git a/src/database/mongo.db.ts b/src/database/mongo.db.ts index c7a85d1..fe1fa65 100644 --- a/src/database/mongo.db.ts +++ b/src/database/mongo.db.ts @@ -9,19 +9,17 @@ import mongoose from 'mongoose'; import { MONGOBD_USER, MONGOBD_PASSWORD } from '@/config/process.config'; import { _log } from '@/utils'; -const connectMongo = function (callback = () => {}) { - mongoose - .connect( - `mongodb+srv://${MONGOBD_USER}:${MONGOBD_PASSWORD}@davidapi.jhhu4ml.mongodb.net/resume-api?retryWrites=true&w=majority&appName=davidAPI`, - ) - .then(() => { - _log(`--------------------`) - _log('MongoDB Connected!') - callback?.(); - }) - .catch((err) => { - _log({ text: `MongoDB Connect failed !!! ${err}`, type: 'error' }) - }); +const MONGO_URI = `mongodb+srv://${MONGOBD_USER}:${MONGOBD_PASSWORD}@davidapi.jhhu4ml.mongodb.net/resume-api?retryWrites=true&w=majority&appName=davidAPI`; + +const connectMongo = async function (callback = () => {}): Promise { + try { + await mongoose.connect(MONGO_URI); + _log('MongoDB Connected!'); + return true; + } catch (e) { + _log({ text: `MongoDB Connect failed !!! ${e}`, type: 'error' }); + return false; + } }; export default connectMongo; diff --git a/src/server.ts b/src/server.ts index c1cdfd4..98e9dc8 100644 --- a/src/server.ts +++ b/src/server.ts @@ -7,7 +7,7 @@ require('module-alias/register'); require('./alias'); import dotenv from 'dotenv'; - import path, { dirname } from 'path'; +import path, { dirname } from 'path'; import express from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; @@ -16,6 +16,7 @@ import session from 'express-session'; import { errorsMiddleware } from '@/middlewares'; import { sessionConfig, corsConfig } from '@/config'; +import { _log } from '@/utils'; import router from '@/routers'; @@ -84,6 +85,13 @@ const runServer = () => { const { LOCAL_PORT = 3001 } = process.env; import connectMongo from '@/database/mongo.db'; -connectMongo(() => { - runServer?.(); -}); +const startServer = async () => { + try { + const isConnected = await connectMongo(); + isConnected && runServer(); + } catch (e) { + _log(`Failed to start server: ${e}`); + } +} + +startServer(); \ No newline at end of file diff --git a/src/utils/bcrypt.ts b/src/utils/bcrypt.ts index beff4cc..cac6022 100644 --- a/src/utils/bcrypt.ts +++ b/src/utils/bcrypt.ts @@ -4,6 +4,7 @@ * Description: */ +import { _log } from '.'; import bcrypt from 'bcrypt'; const saltRounds = 10; // số vòng mã hóa @@ -14,7 +15,7 @@ export const bcryptGenerateSalt = async (pass: string): Promise => { const hash = await bcrypt.hash(pass, salt); return hash; } catch (e) { - console.error('Error hashing password:', e); + _log('Error hashing password'); throw new Error('Failed to hash password'); } }; @@ -24,7 +25,7 @@ export const bcryptCompareHash = async (str: string, hash: string): Promise