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

feat-#3: Made the entire backend code from javascript to typescript #466

Merged
merged 6 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ backend/node_modules
/node_modules
coverage/
.idea/
backend/dist
package-lock.json
2 changes: 0 additions & 2 deletions backend/api/index.js

This file was deleted.

2 changes: 2 additions & 0 deletions backend/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import app from '../app';
export default app;
14 changes: 7 additions & 7 deletions backend/app.js → backend/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
import { FRONTEND_URL } from './config/utils.js';
import authRouter from './routes/auth.js';
import postsRouter from './routes/posts.js';
import userRouter from './routes/user.js';
import errorMiddleware from './middlewares/error-middleware.js';
import passport from './config/passport.js';
import authRouter from './routes/auth';
import postsRouter from './routes/posts';
import userRouter from './routes/user';
import errorMiddleware from './middlewares/error-middleware';
import passport from './config/passport';
import session from 'express-session';
import { FRONTEND_URL } from './config/utils';

const app = express();

app.use(
cors({
// added origin
origin: [FRONTEND_URL, 'http://localhost:3000'],
origin: [FRONTEND_URL as string, 'http://localhost:3000'],
credentials: true,
})
);
Expand Down
8 changes: 4 additions & 4 deletions backend/config/db.js → backend/config/db.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import mongoose from 'mongoose';
import { MONGODB_URI } from './utils.js';
import mongoose, { AnyArray } from 'mongoose';
import { MONGODB_URI } from './utils';

export default async function connectDB() {
try {
await mongoose.connect(MONGODB_URI, {
await mongoose.connect(MONGODB_URI as string, {
dbName: 'wanderlust',
});
console.log(`Database connected: ${MONGODB_URI}`);
} catch (err) {
} catch (err: any) {
console.error(err.message);
process.exit(1);
}
Expand Down
11 changes: 5 additions & 6 deletions backend/config/passport.js → backend/config/passport.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import User from '../models/user.js';

import User from '../models/user';
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
clientID: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
callbackURL: `${process.env.BACKEND_URL}/api/auth/google/callback`,
},
async (accessToken, refreshToken, profile, done) => {
async (accessToken: string, refreshToken: string, profile: any, done: any) => {
try {
let user = await User.findOne({ googleId: profile.id });

Expand Down Expand Up @@ -40,7 +39,7 @@ passport.use(
)
);

passport.serializeUser((user, done) => done(null, user.id));
passport.serializeUser((user: any, done) => done(null, user.id));

passport.deserializeUser(async (id, done) => {
try {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import User from '../models/user.js';
import User from '../models/user';
import jwt from 'jsonwebtoken';
import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants.js';
import { cookieOptions } from '../utils/cookie_options.js';
import { JWT_SECRET } from '../config/utils.js';
import { ApiError } from '../utils/api-error.js';
import { ApiResponse } from '../utils/api-response.js';
import { asyncHandler } from '../utils/async-handler.js';
import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants';
import { cookieOptions } from '../utils/cookie_options';
import { JWT_SECRET } from '../config/utils';
import { ApiError } from '../utils/api-error';
import { ApiResponse } from '../utils/api-response';
import { asyncHandler } from '../utils/async-handler';
import { NextFunction, Request, Response } from 'express';

//REGULAR EMAIL PASSWORD STRATEGY
//1.Sign Up
export const signUpWithEmail = asyncHandler(async (req, res) => {

export const signUpWithEmail = asyncHandler(async (req: Request, res: Response) => {
const { userName, fullName, email, password } = req.body;
if (!userName || !fullName || !email || !password) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS,
});
}

const existingUser = await User.findOne({
Expand All @@ -21,10 +26,16 @@ export const signUpWithEmail = asyncHandler(async (req, res) => {

if (existingUser) {
if (existingUser.userName === userName) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.USERS.USER_USERNAME_EXISTS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.USERS.USER_USERNAME_EXISTS,
});
}
if (existingUser.email === email) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.USERS.USER_EMAIL_EXISTS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.USERS.USER_EMAIL_EXISTS,
});
}
}

Expand All @@ -37,12 +48,15 @@ export const signUpWithEmail = asyncHandler(async (req, res) => {

try {
await user.validate();
} catch (error) {
const validationErrors = [];
} catch (error: any) {
const validationErrors: any = [];
for (const key in error.errors) {
validationErrors.push(error.errors[key].message);
validationErrors.push(error.errors[key].message as never);
}
throw new ApiError(HTTP_STATUS.BAD_REQUEST, validationErrors.join(', '));
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
errors: validationErrors.join(', '),
});
}

const accessToken = await user.generateAccessToken();
Expand Down Expand Up @@ -71,24 +85,33 @@ export const signUpWithEmail = asyncHandler(async (req, res) => {
});

//2.Sign In
export const signInWithEmailOrUsername = asyncHandler(async (req, res) => {
export const signInWithEmailOrUsername = asyncHandler(async (req: Request, res: Response) => {
const { userNameOrEmail, password } = req.body;
if (!userNameOrEmail || !password) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS,
});
}

const user = await User.findOne({
$or: [{ email: userNameOrEmail }, { userName: userNameOrEmail }],
}).select('+password');

if (!user) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.USERS.USER_NOT_EXISTS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.USERS.USER_NOT_EXISTS,
});
}

const isCorrectPassword = await user.isPasswordCorrect(password);

if (!isCorrectPassword) {
throw new ApiError(HTTP_STATUS.UNAUTHORIZED, RESPONSE_MESSAGES.USERS.INVALID_PASSWORD);
throw new ApiError({
status: HTTP_STATUS.UNAUTHORIZED,
message: RESPONSE_MESSAGES.USERS.INVALID_PASSWORD,
});
}
const accessToken = await user.generateAccessToken();
const refreshToken = await user.generateRefreshToken();
Expand All @@ -115,7 +138,7 @@ export const signInWithEmailOrUsername = asyncHandler(async (req, res) => {
});

//Sign Out
export const signOutUser = asyncHandler(async (req, res, next) => {
export const signOutUser = asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
await User.findByIdAndUpdate(
req.user?._id,
{
Expand All @@ -129,9 +152,14 @@ export const signOutUser = asyncHandler(async (req, res, next) => {
);

// Passport.js logout
req.logout((err) => {
req.logout((err: any) => {
if (err) {
return next(new ApiError(HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Logout failed'));
return next(
new ApiError({
status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
message: 'Logout failed',
})
);
}

res
Expand All @@ -143,7 +171,7 @@ export const signOutUser = asyncHandler(async (req, res, next) => {
});
});
// check user
export const isLoggedIn = asyncHandler(async (req, res) => {
export const isLoggedIn = asyncHandler(async (req: Request, res: Response) => {
let access_token = req.cookies?.access_token;
let refresh_token = req.cookies?.refresh_token;
const { _id } = req.params;
Expand All @@ -155,18 +183,22 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
}
if (access_token) {
try {
await jwt.verify(access_token, JWT_SECRET);
if (JWT_SECRET) {
await jwt.verify(access_token, JWT_SECRET);
}
return res
.status(HTTP_STATUS.OK)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error) {
} catch (error: any) {
console.log('Access token verification error:', error.message);
}
}
// If access token is not valid, check the refresh token
if (refresh_token) {
try {
await jwt.verify(refresh_token, JWT_SECRET);
if (JWT_SECRET) {
await jwt.verify(refresh_token, JWT_SECRET);
}
const user = await User.findById(_id);
if (!user) {
return res
Expand All @@ -180,7 +212,7 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
.status(HTTP_STATUS.OK)
.cookie('access_token', access_token, cookieOptions)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error) {
} catch (error: any) {
console.log('Refresh token verification error:', error.message);
}
}
Expand All @@ -202,7 +234,9 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
}

try {
await jwt.verify(refreshToken, JWT_SECRET);
if (JWT_SECRET) {
await jwt.verify(refreshToken, JWT_SECRET);
}
access_token = await user.generateAccessToken();
refresh_token = await user.generateRefreshToken();

Expand All @@ -213,7 +247,7 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
.cookie('access_token', access_token, cookieOptions)
.cookie('refresh_token', refresh_token, cookieOptions)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error) {
} catch (error: any) {
return res
.status(HTTP_STATUS.UNAUTHORIZED)
.json(
Expand Down
Loading
Loading