Skip to content

Commit

Permalink
refactor: Refactor backend and client code
Browse files Browse the repository at this point in the history
  • Loading branch information
sayinmehmet47 committed Mar 29, 2024
1 parent 3e13189 commit 0ff3442
Show file tree
Hide file tree
Showing 30 changed files with 710 additions and 495 deletions.
27 changes: 10 additions & 17 deletions backend/app.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,31 @@
import { Request, Response } from 'express';
import 'express-async-errors';
const { updateMetrics } = require('./metrics');

import routes from './routes';
import { json } from 'body-parser';

import express from 'express';
import cors from 'cors';
import path from 'path';
import { NotFoundError } from './errors/not-found-error';
import { errorHandler } from './middleware/error-handler';
import { updateMetrics } from './metrics';

const app = express();

app.set('trust proxy', true);
app.use(json());

const books = require('./routes/api/books');
const user = require('./routes/api/user');
const messages = require('./routes/api/messages');
const subscription = require('./routes/api/subscription');

app.use(express.json());

const corsOptions = {
origin: '*',
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
};

app.use(cors(corsOptions));
app.use(
cors({
origin: 'http://localhost:3000',
credentials: true,
})
);

app.use('/api/books', books);
app.use('/api/user', user);
app.use('/api/messages', messages);
app.use('/api/subscription', subscription);
app.use('/api', routes);

app.use(updateMetrics);

Expand Down
109 changes: 109 additions & 0 deletions backend/controllers/books.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { NextFunction, Request, Response } from 'express';
import {
addNewBook,
deleteBook,
getAllBooksService,
getBookById,
getRecentlyAddedBooks,
searchBooksService,
updateBook,
updateCategories,
} from '../services/book';

export const getAllBooksController = async (req: Request, res: Response) => {
try {
const books = await getAllBooksService(req);
res.json(books);
} catch (err) {
if (err instanceof Error) {
res.status(500).json({ error: err.message });
} else {
res.status(500).json({ error: 'An unknown error occurred' });
}
}
};

export const searchBooksController = async (req: Request, res: Response) => {
try {
const books = await searchBooksService(req);
res.json(books);
} catch (err) {
if (err instanceof Error) {
res.status(500).json({ error: err.message });
} else {
res.status(500).json({ error: 'An unknown error occurred' });
}
}
};
export const addBookController = async (req: Request, res: Response) => {
try {
const books = await addNewBook(req);

res.status(201).json(books);
} catch (err) {
if (err instanceof Error) {
res.status(500).json({ error: err.message });
} else {
res.status(500).json({ error: 'An unknown error occurred' });
}
}
};

export const recentlyAddedBooksController = async (
req: Request,
res: Response
) => {
try {
const books = await getRecentlyAddedBooks();
res.json(books);
} catch (err) {
console.log(err);
res.status(500).json({ error: 'An unknown error occurred' });
}
};

export const deleteBookController = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const book = await deleteBook(req);
res.status(201).json(book);
} catch (err) {
next(err);
}
};

export const getBookByIdController = async (req: Request, res: Response) => {
try {
const book = await getBookById(req);
res.status(201).json(book);
} catch (err) {
console.log(err);
res.status(500).json({ error: 'An unknown error occurred' });
}
};

export const updateCategoriesController = async (
req: Request,
res: Response
) => {
try {
await updateCategories();
res.status(200).send('Categories updated');
} catch (err) {
console.log(err);
res.status(500).json({ error: 'An unknown error occurred' });
}
};

export const updateBookController = async (req: Request, res: Response) => {
try {
const book = await updateBook(req);
res.status(201).json(book);
} catch (err) {
console.log(err);
res.status(500).json({ error: 'An unknown error occurred' });
}
};
33 changes: 33 additions & 0 deletions backend/controllers/messages.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Request, Response } from 'express';
import {
createUserMessage,
deleteMessage,
getUserMessages,
} from '../services/message/userMessages.service';

export const getUserMessagesController = async (
req: Request,
res: Response
) => {
const userMessages = await getUserMessages();
res.json(userMessages);
};

export const createUserMessageController = async (
req: Request,
res: Response
) => {
const { text, sender } = req.body;
try {
const userMessages = await createUserMessage(text, sender);
res.status(201).json(userMessages);
} catch (error) {
console.log(error);
}
};

export const deleteMessageController = async (req: Request, res: Response) => {
const { id } = req.body;
const result = await deleteMessage(id, req.body.user.isAdmin);
res.status(201).json(result);
};
38 changes: 38 additions & 0 deletions backend/controllers/user.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Request, Response } from 'express';
import {
authenticateUser,
loginUser,
logoutUser,
registerUser,
} from '../services/user';

export const loginController = async (req: Request, res: Response) => {
const { username, password } = req.body;
const result = await loginUser(username, password);
res.status(201).json(result);
};

export const registerController = async (req: Request, res: Response) => {
const { username, email, password, isAdmin = false } = req.body;
const result = await registerUser(username, email, password, isAdmin);
res.status(201).json(result);
};

export const authController = async (req: Request, res: Response) => {
try {
const token = req.header('Authorization')?.split(' ')[1] || '';
const result = await authenticateUser(req.body.user.id, token);
res.json(result);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
};

export const logoutController = async (req: Request, res: Response) => {
try {
await logoutUser(req.body.user.id);
res.status(201).json({});
} catch (err: any) {
res.status(500).json({ message: 'User logged out successfully' });
}
};
4 changes: 1 addition & 3 deletions backend/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,4 @@ app.get(
}
);

module.exports = {
updateMetrics,
};
export { app, updateMetrics };
5 changes: 2 additions & 3 deletions backend/routes/api/__test__/books.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ it('should not unauthorized users can upload new book', async () => {

it('should authorized users can upload new book', async () => {
const { token, sender } = await global.signin();

await request(app)
.post('/api/books/addNewBook')
.set('Authorization', `Bearer ${token}`)
Expand Down Expand Up @@ -114,9 +115,7 @@ it('should get all the books paginated', async () => {
const allBooks = await request(app)
.get(`/api/books/allBooks/?page=0&language=`)
.set('Authorization', `Bearer ${token}`)
.expect(201);

console.log(allBooks.body);
.expect(200);

expect(allBooks.body.total).toEqual(2);
expect(allBooks.body.results[0].name).toEqual(book2.body.name);
Expand Down
Loading

0 comments on commit 0ff3442

Please sign in to comment.