Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor compose #484

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ backend/node_modules
coverage/
.idea/
backend/dist
package-lock.json
package-lock.json
**/logs
3 changes: 1 addition & 2 deletions .husky/commit-msg
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
#! /bin/bash

commit_msg_file="$1"
commit_msg=$(cat "$commit_msg_file")
Expand Down
4 changes: 1 addition & 3 deletions .husky/pre-commit
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
#!/usr/bin/env sh

. "$(dirname -- "$0")/_/husky.sh"
#! /bin/bash

cd frontend
echo [FRONTEND] Running the prettier format for you.
Expand Down
26 changes: 26 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Google Console identity
proyecto de Devops auth: [Google cloud](https://console.cloud.google.com/apis/credentials?project=devops-final-1731180691822)

si no tiene permisos me avisan y los agrego luego de agregado se descargan las credenciales de ese proyecto, luego deben agregarlas en su zhsrc o bashrc dependiendo de su consola

export GOOGLE_CLIENT_ID=
export GOOGLE_CLIENT_SECRET=

# Docker

## Crear contenedores
docker run --name mongodb -p 27017:27017 -d mongo:8.0.3-noble
docker run -d --name redis -p 6379:6379 redis

## Tools
```bash
docker run -it \
--name mongo-express \
--link mongodb:mongo \
-p 8081:8081 \
-e ME_CONFIG_MONGODB_URL="mongodb://mongo:27017" \
-e ME_CONFIG_OPTIONS_EDITORTHEME="ambiance" \
-e ME_CONFIG_BASICAUTH_USERNAME="user" \
-e ME_CONFIG_BASICAUTH_PASSWORD="pass" \
mongo-express
```
7 changes: 4 additions & 3 deletions backend/config/db.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import mongoose, { AnyArray } from 'mongoose';
import { MONGODB_URI } from './utils.js';
import logger from './logger.js';

export default async function connectDB() {
try {
await mongoose.connect(MONGODB_URI as string, {
dbName: 'wanderlust',
});
console.log(`Database connected: ${MONGODB_URI}`);
logger.info(`Database connected: ${MONGODB_URI}`);
} catch (err: any) {
console.error(err.message);
logger.error(err.message);
process.exit(1);
}

const dbConnection = mongoose.connection;

dbConnection.on('error', (err) => {
console.error(`connection error: ${err}`);
logger.error(`connection error: ${err}`);
});
return;
}
36 changes: 36 additions & 0 deletions backend/config/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { createLogger, transports, format } from 'winston';

const options = {
file: {
level: 'error',
filename: `./logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
handleExceptions: true,
json: false,
colorize: true,
},
};

const alignColorsAndTime = format.combine(
format.colorize({
all: true,
}),
format.label({
label: 'Backend',
}),
format.timestamp({
format: 'DD-MMM-YYYY HH:mm:ss',
}),
format.printf((info) => `[${info.timestamp} - ${info.label}] ${info.level}: ${info.message}`)
);

export default createLogger({
format: alignColorsAndTime,
transports: [new transports.File(options.file), new transports.Console(options.console)],
});
34 changes: 21 additions & 13 deletions backend/config/utils.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import dotenv from 'dotenv';
dotenv.config();
import logger from './logger.js';

const PORT = process.env.PORT;
const MONGODB_URI = process.env.MONGODB_URI;
const REDIS_URL = process.env.REDIS_URL;
const ACCESS_COOKIE_MAXAGE = process.env.ACCESS_COOKIE_MAXAGE;
const ACCESS_TOKEN_EXPIRES_IN = process.env.ACCESS_TOKEN_EXPIRES_IN;
const REFRESH_COOKIE_MAXAGE = process.env.REFRESH_COOKIE_MAXAGE;
const REFRESH_TOKEN_EXPIRES_IN = process.env.REFRESH_TOKEN_EXPIRES_IN;
const JWT_SECRET = process.env.JWT_SECRET;
const FRONTEND_URL = process.env.FRONTEND_URL;
const NODE_ENV = process.env.NODE_ENV;
//dotenv.config({ path: `.env.${process.env.NODE_ENV}` });
dotenv.config({ path: '.env' });

export {
const options = {
PORT: process.env.PORT,
MONGODB_URI: process.env.MONGODB_URI,
REDIS_URL: process.env.REDIS_URL,
ACCESS_COOKIE_MAXAGE: process.env.ACCESS_COOKIE_MAXAGE,
ACCESS_TOKEN_EXPIRES_IN: process.env.ACCESS_TOKEN_EXPIRES_IN,
REFRESH_COOKIE_MAXAGE: process.env.REFRESH_COOKIE_MAXAGE,
REFRESH_TOKEN_EXPIRES_IN: process.env.REFRESH_TOKEN_EXPIRES_IN,
JWT_SECRET: process.env.JWT_SECRET,
FRONTEND_URL: process.env.FRONTEND_URL,
// NODE_ENV: process.env.NODE_ENV || 'sample',
NODE_ENV: process.env.NODE_ENV,
};
logger.info(`Google strategy => Client id: ${process.env.GOOGLE_CLIENT_ID}`);
logger.info(`Configurations vairables: ${JSON.stringify(options)}`);

export const {
MONGODB_URI,
PORT,
REDIS_URL,
Expand All @@ -23,4 +31,4 @@ export {
JWT_SECRET,
FRONTEND_URL,
NODE_ENV,
};
} = options;
5 changes: 3 additions & 2 deletions backend/controllers/auth-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ApiError } from '../utils/api-error.js';
import { ApiResponse } from '../utils/api-response.js';
import { asyncHandler } from '../utils/async-handler.js';
import { NextFunction, Request, Response } from 'express';
import logger from '../config/logger.js';

//REGULAR EMAIL PASSWORD STRATEGY
//1.Sign Up
Expand Down Expand Up @@ -190,7 +191,7 @@ export const isLoggedIn = asyncHandler(async (req: Request, res: Response) => {
.status(HTTP_STATUS.OK)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error: any) {
console.log('Access token verification error:', error.message);
logger.error(`Access token verification error: ${error.message}`);
}
}
// If access token is not valid, check the refresh token
Expand All @@ -213,7 +214,7 @@ export const isLoggedIn = asyncHandler(async (req: Request, res: Response) => {
.cookie('access_token', access_token, cookieOptions)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error: any) {
console.log('Refresh token verification error:', error.message);
logger.error(`Refresh token verification error: ${error.message}`);
}
}

Expand Down
7 changes: 4 additions & 3 deletions backend/controllers/user-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants.js';
import User from '../models/user.js';
import { Role } from '../types/role-type.js';
import { Request, Response } from 'express';
import logger from '../config/logger.js';

export const getAllUserHandler = async (req: Request, res: Response) => {
try {
const users = await User.find().select('_id fullName role email');
return res.status(HTTP_STATUS.OK).json({ users });
} catch (error) {
console.log(error);
logger.error(error);
res
.status(HTTP_STATUS.INTERNAL_SERVER_ERROR)
.json({ message: RESPONSE_MESSAGES.COMMON.INTERNAL_SERVER_ERROR });
Expand All @@ -34,7 +35,7 @@ export const changeUserRoleHandler = async (req: Request, res: Response) => {
}
return res.status(HTTP_STATUS.OK).json({ message: RESPONSE_MESSAGES.USERS.UPDATE });
} catch (error) {
console.log(error);
logger.error(error);
res
.status(HTTP_STATUS.INTERNAL_SERVER_ERROR)
.json({ message: RESPONSE_MESSAGES.COMMON.INTERNAL_SERVER_ERROR, error: error });
Expand All @@ -51,7 +52,7 @@ export const deleteUserHandler = async (req: Request, res: Response) => {
.json({ message: RESPONSE_MESSAGES.USERS.USER_NOT_EXISTS });
res.status(HTTP_STATUS.NO_CONTENT).json({ message: RESPONSE_MESSAGES.USERS.DELETED });
} catch (error) {
console.log(error);
logger.error(error);
res
.status(HTTP_STATUS.INTERNAL_SERVER_ERROR)
.json({ message: RESPONSE_MESSAGES.COMMON.INTERNAL_SERVER_ERROR, error: error });
Expand Down
4 changes: 2 additions & 2 deletions backend/middlewares/auth-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants.js';
import jwt from 'jsonwebtoken';
import { Role } from '../types/role-type.js';
import User from '../models/user.js';

import logger from '../config/logger.js';
import { Request, Response, NextFunction } from 'express';
import { ObjectId } from 'mongoose';

Expand All @@ -28,7 +28,7 @@ export const authMiddleware = async (req: Request, res: Response, next: NextFunc
req.user = await User.findById(_id);
next();
} catch (error: any) {
console.log('Token verification error:', error);
logger.error(`Token verification error: ${error}`);
return next(
new ApiError({
status: HTTP_STATUS.FORBIDDEN,
Expand Down
4 changes: 2 additions & 2 deletions backend/middlewares/post-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Post from '../models/post.js';
import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants.js';
import { Request, Response, NextFunction } from 'express';

import logger from '../config/logger.js';
export const isAuthorMiddleware = async (req: Request, res: Response, next: NextFunction) => {
try {
const userId = req.user._id;
Expand All @@ -11,7 +11,7 @@ export const isAuthorMiddleware = async (req: Request, res: Response, next: Next
return res.status(HTTP_STATUS.NOT_FOUND).json({ message: RESPONSE_MESSAGES.POSTS.NOT_FOUND });
}

console.log(post.authorId, userId);
logger.debug(`authorId => ${post.authorId.toString()}, userId => ${userId}`);
if (post.authorId.toString() !== userId) {
return res
.status(HTTP_STATUS.FORBIDDEN)
Expand Down
13 changes: 8 additions & 5 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@
"express-session": "^1.18.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1",
"nodemon": "^3.1.7",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
"redis": "^4.6.13"
"redis": "^4.6.13",
"winston": "^3.16.0"
},
"lint-staged": {
"**/*.{js,ts,jsx,tsx}": [
Expand All @@ -37,9 +38,10 @@
]
},
"scripts": {
"build": "tsc",
"test": "jest --watchAll --detectOpenHandles --verbose --coverage ",
"start": "node server.js",
"dev": "nodemon server.js",
"start": "npm run build && node dist/server.js",
"dev": "nodemon dist/server.js",
"check": "prettier --check .",
"format": "prettier --write .",
"vercel-build": "echo yay"
Expand Down Expand Up @@ -69,6 +71,7 @@
"lint-staged": "^15.2.2",
"prettier": "^3.2.5",
"supertest": "^6.3.3",
"ts-node": "^10.9.2",
"typescript": "^5.5.4"
}
}
}
5 changes: 3 additions & 2 deletions backend/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from './config/logger.js';
import app from './app.js';
import connectDB from './config/db.js';
import { PORT } from './config/utils.js';
Expand All @@ -12,11 +13,11 @@ const server = () => {
connectDB()
.then(() => {
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
logger.info(`Server is running on port ${port}`);
});
})
.catch((error) => {
console.log('MongoDB connection failed:', error);
logger.error('MongoDB connection failed:', error);
});
};
server();
Expand Down
7 changes: 4 additions & 3 deletions backend/services/redis.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createClient } from 'redis';
import { REDIS_URL } from '../config/utils.js';
import logger from '../config/logger.js';

let redis: any = null;
export async function connectToRedis() {
Expand All @@ -9,12 +10,12 @@ export async function connectToRedis() {
url: REDIS_URL,
disableOfflineQueue: true,
}).connect();
console.log('Redis Connected: ' + REDIS_URL);
logger.info('Redis Connected: ' + REDIS_URL);
} else {
console.log('Redis not configured, cache disabled.');
logger.warn('Redis not configured, cache disabled.');
}
} catch (error: any) {
console.error('Error connecting to Redis:', error.message);
logger.error('Error connecting to Redis:', error.message);
}
}

Expand Down
3 changes: 2 additions & 1 deletion backend/utils/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { retrieveDataFromCache } from './cache-posts.js';
import { HTTP_STATUS } from './constants.js';
import { Request, Response, NextFunction } from 'express';
import logger from '../config/logger.js';

export const cacheHandler =
(key: string) => async (req: Request, res: Response, next: NextFunction) => {
try {
const cachedData = await retrieveDataFromCache(key);
if (cachedData) {
console.log(`Getting cached data for key: ${key}`);
logger.info(`Getting cached data for key: ${key}`);
return res.status(HTTP_STATUS.OK).json(cachedData);
}
next(); // Proceed to the route handler if data is not cached
Expand Down
Loading
Loading