Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sanandnarayan/fa8e9c4f04ce7c738f573a9a251522fc to your computer and use it in GitHub Desktop.
Save sanandnarayan/fa8e9c4f04ce7c738f573a9a251522fc to your computer and use it in GitHub Desktop.
import Decimal from 'simple-decimal-money';
export default {
async fetch(request) {
const url = new URL(request.url);
// Check if the request is for addition
if (url.pathname === '/add') {
// Get query parameters
const num1 = url.searchParams.get('num1');
const num2 = url.searchParams.get('num2');
// Validate parameters
if (!num1 || !num2) {
return new Response(JSON.stringify({
error: "Missing parameters. Use /add?num1=x&num2=y"
}), {
status: 400,
headers: { "content-type": "application/json;charset=UTF-8" }
});
}
try {
// Use the bundled Decimal library for precise addition
const decimal1 = new Decimal(num1);
const decimal2 = new Decimal(num2);
const result = decimal1.add(decimal2);
return new Response(JSON.stringify({
num1: decimal1.toString(),
num2: decimal2.toString(),
result: result.toString()
}), {
headers: { "content-type": "application/json;charset=UTF-8" }
});
} catch (error) {
return new Response(JSON.stringify({
error: "Invalid numbers provided",
message: error.message
}), {
status: 400,
headers: { "content-type": "application/json;charset=UTF-8" }
});
}
}
// Default response
return new Response(JSON.stringify({
message: "Welcome to Decimal Calculator API",
usage: "/add?num1=x&num2=y"
}), {
headers: { "content-type": "application/json;charset=UTF-8" }
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment