Skip to content

Commit

Permalink
Merge pull request #38 from PedroCavalheiro/patch-5
Browse files Browse the repository at this point in the history
Added typescript types
  • Loading branch information
Unisergius authored Mar 22, 2024
2 parents aa40f5b + cd0a1c2 commit cdd34d7
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as express from 'express';
import express, { Express, Request, Response } from 'express';
import {
addTwoNumbers,
divideTwoNumbers,
Expand All @@ -7,40 +7,45 @@ import {
subtractTwoNumbers,
} from './math.handler';

const app = express();
const app: Express = express();

const operations = {
'sum': addTwoNumbers,
interface Operations {
[key: string]: (a: number, b: number) => number;
}

const operations: Operations = {
'add': addTwoNumbers, // Ensure your math handlers are properly typed in their respective files
'div': divideTwoNumbers,
'subtract': subtractTwoNumbers,
'multiply': multiplyTwoNumbers,
'power': powerTwoNumbers,
};

// A helper function for validating numeric input
const validateNumbers = (a: string, b: string, res: express.Response): boolean => {
if (isNaN(Number(a)) || isNaN(Number(b))) {
const validateNumbers = (a: string, b: string, res: Response): boolean => {
const numRegex: RegExp = /^-?\d+\.?\d*$/;
if (!numRegex.test(a) || !numRegex.test(b)) {
res.status(400).json({ error: 'Invalid input, numbers required.' });
return false;
}
return true;
};

app.get('/:operation/:a/:b', (req: express.Request, res: express.Response) => {
app.get('/:operation/:a/:b', (req: Request, res: Response) => {
const { operation, a, b } = req.params;

if (!validateNumbers(a, b, res)) return;
if (operation === 'div' && Number(b) === 0) {
res.status(400).json({ error: 'Division by zero is not allowed.' });
return;
}
const operationFunction = operations[operation];
if (!operationFunction) {
res.status(404).json({ error: 'Operation not supported.' });
return;
}

const result = operationFunction(Number(a), Number(b));
if (!validateNumbers(a, b, res)) return;
if (operation === 'div' && Number(b) === 0) {
res.status(400).json({ error: 'Division by zero is not allowed.' });
return;
}

const result: number = operationFunction(Number(a), Number(b));
res.json({
message: `${operation.charAt(0).toUpperCase() + operation.slice(1)} Operation`,
operation: 'success',
Expand All @@ -50,10 +55,10 @@ app.get('/:operation/:a/:b', (req: express.Request, res: express.Response) => {
});
});

app.get('/', (_req, res) => {
app.get('/', (_req: Request, res: Response) => {
res.json({
message: 'Welcome to the Math API',
endpoints: Object.keys(operations).map(op => ({
endpoints: Object.keys(operations).map((op: string) => ({
path: `/${op}/:a/:b`,
description: `Performs the ${op} operation on two numbers.`,
})),
Expand Down

0 comments on commit cdd34d7

Please sign in to comment.