Skip to content

Commit

Permalink
error handler middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
patrick-carmo committed Apr 9, 2024
1 parent 980325d commit 0d68b3c
Show file tree
Hide file tree
Showing 9 changed files with 200 additions and 238 deletions.
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"dotenv": "^16.4.5",
"env-var": "^7.4.1",
"express": "^4.19.2",
"express-async-errors": "^3.1.1",
"joi": "^17.12.2",
"knex": "^3.1.0",
"pg": "^8.11.3",
Expand Down
103 changes: 35 additions & 68 deletions src/controllers/currencyController.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,25 @@
import { Request, Response } from "express";
import { currencyService } from "../services/currencyService";
import { Conversion, Currency } from "../types/currency";
import { BadRequestError } from "../utils/apiError";

const listCurrencies = async (_: Request, res: Response) => {
try {
const currencies = await currencyService.getCurrencies();

return res.status(200).json(currencies);
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
const currencies = await currencyService.getCurrencies();
return res.status(200).json(currencies);
};

const getCurrency = async (req: Request, res: Response) => {
const code = (req.params.code as string).toUpperCase();

try {
const supportedCurrencies =
await currencyService.getSupportedCurrencies();
const supportedCurrencies = await currencyService.getSupportedCurrencies();

if (!supportedCurrencies.includes(code)) {
return res
.status(400)
.json({ message: "The currency is not supported" });
}
if (!supportedCurrencies.includes(code)) {
throw new BadRequestError("The currency is not supported");
}

const currency = await currencyService.getCurrency(code);
const currency = await currencyService.getCurrency(code);

return res.status(200).json(currency);
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
return res.status(200).json(currency);
};

const convertCurrency = async (req: Request, res: Response) => {
Expand All @@ -43,36 +32,29 @@ const convertCurrency = async (req: Request, res: Response) => {
const uppercaseFrom = from.toUpperCase();
const uppercaseTo = to.toUpperCase();

try {
const supportedCurrencies =
await currencyService.getSupportedCurrencies();

if (!supportedCurrencies.includes(uppercaseFrom)) {
return res
.status(400)
.json({ message: "The currency from is not supported" });
}

if (!supportedCurrencies.includes(uppercaseTo)) {
return res
.status(400)
.json({ message: "The currency to is not supported" });
}

const data: Conversion = {
from: uppercaseFrom,
to: uppercaseTo,
amount,
};

const conversion: Conversion = await currencyService.getConversion(
data
const supportedCurrencies = await currencyService.getSupportedCurrencies();

if (!supportedCurrencies.includes(uppercaseFrom)) {
throw new BadRequestError(
`The currency ${uppercaseFrom} is not supported`
);
}

return res.status(200).json(conversion);
} catch (error: any) {
return res.status(500).json({ message: error.message });
if (!supportedCurrencies.includes(uppercaseTo)) {
throw new BadRequestError(
`The currency ${uppercaseTo} is not supported`
);
}

const data: Conversion = {
from: uppercaseFrom,
to: uppercaseTo,
amount,
};

const conversion: Conversion = await currencyService.getConversion(data);

return res.status(200).json(conversion);
};

const createCurrency = async (req: Request, res: Response) => {
Expand All @@ -84,13 +66,8 @@ const createCurrency = async (req: Request, res: Response) => {
value,
};

try {
await currencyService.createCurrency(currency);

return res.status(201).json(currency);
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
await currencyService.createCurrency(currency);
return res.status(201).json(currency);
};

const updateCurrency = async (req: Request, res: Response) => {
Expand All @@ -103,25 +80,15 @@ const updateCurrency = async (req: Request, res: Response) => {
value,
};

try {
await currencyService.updateCurrency(codeParams, currency);

return res.status(204).send();
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
await currencyService.updateCurrency(codeParams, currency);
return res.status(204).send();
};

const deleteCurrency = async (req: Request, res: Response) => {
const code = (req.params.code as string).toUpperCase();

try {
await currencyService.deleteCurrency(code);

return res.status(204).send();
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
await currencyService.deleteCurrency(code);
return res.status(204).send();
};

export const currencyController = {
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import "dotenv/config";
import 'express-async-errors'
import env from "./config/envConfig";
import express from "express";
import redis from "./database/redis";

import currencyRoutes from "./routes/currencyRoute";
import errorMiddleware from "./middlewares/error";

redis.connect();

const app = express();

app.use(express.json());

app.use(currencyRoutes);
app.use(errorMiddleware)

app.listen(env.PORT, () => console.log(`Server running on port ${env.PORT}`));
14 changes: 14 additions & 0 deletions src/middlewares/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Request, Response, NextFunction } from "express";
import { ApiError } from "../utils/apiError";

export default function errorMiddleware(
error: Error & Partial<ApiError>,
req: Request,
res: Response,
next: NextFunction
) {
const statusCode = error.statusCode ?? 500;
const message =
statusCode === 500 ? "Internal server error" : error.message;
res.status(statusCode).json({ message });
}
8 changes: 3 additions & 5 deletions src/middlewares/requestValidation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Request, Response, NextFunction } from "express";
import { ObjectSchema } from "joi";
import { BadRequestError } from "../utils/apiError";

const requestValidation =
(schema: ObjectSchema) =>
Expand All @@ -8,11 +9,8 @@ const requestValidation =
const params = Object.keys(req.params).length;
const query = Object.keys(req.query).length;
if (req.method !== "GET" && !body && !params && !query) {
return res
.status(400)
.json({ message: "Please fill out all the fields" });
throw new BadRequestError("Please fill out all the fields");
}

try {
if (body) {
await schema.validateAsync({ body: req.body });
Expand All @@ -26,7 +24,7 @@ const requestValidation =

return next();
} catch (error: any) {
return res.status(400).json({ message: error.message });
throw new BadRequestError(error.message);
}
};

Expand Down
1 change: 0 additions & 1 deletion src/routes/currencyRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Router } from "express";
import { currencyController } from "../controllers/currencyController";
import joi from "../middlewares/requestValidation";
import { schema } from "../models/joiCurrency";
import redis from "../database/redis";

const route = Router();

Expand Down
Loading

0 comments on commit 0d68b3c

Please sign in to comment.