Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/__tests__/database/mongo.db.ts
Original file line number Diff line number Diff line change
@@ -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',
});
});
});
24 changes: 11 additions & 13 deletions src/database/mongo.db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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;
16 changes: 12 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';

Expand Down Expand Up @@ -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();
5 changes: 3 additions & 2 deletions src/utils/bcrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* Description:
*/

import { _log } from '.';
import bcrypt from 'bcrypt';

const saltRounds = 10; // số vòng mã hóa
Expand All @@ -14,7 +15,7 @@ export const bcryptGenerateSalt = async (pass: string): Promise<string> => {
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');
}
};
Expand All @@ -24,7 +25,7 @@ export const bcryptCompareHash = async (str: string, hash: string): Promise<bool
try {
return Boolean(await bcrypt.compare(str, hash)); // make sure alway return boolean
} catch (error) {
console.error('Error comparing hash:', error);
_log('Error comparing hash:');
return false;
}
};