Skip to content

Commit

Permalink
download: Refactor and add more error handling in index.js
Browse files Browse the repository at this point in the history
  • Loading branch information
DeeDeeG committed Feb 2, 2024
1 parent 72ea5b7 commit 007e7a2
Showing 1 changed file with 40 additions and 11 deletions.
51 changes: 40 additions & 11 deletions microservices/download/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,55 @@ const utils = require("./utils.js");
const port = parseInt(process.env.PORT) || 8080;

const server = http.createServer(async (req, res) => {
// Since req.url is our URL pluse query params, lets split them first.
const path = req.url.split("?");
if (typeof req?.url !== "string"){
// Not sure if this error condition is even possible, but handling it anyway
await utils.displayError(req, res, {
code: 500,
msg: "Internal Server Error: Misformed URL"
});
console.log("Download Returned 500 due to the requested URL not being received as a string internally");
return;
}

// Since req.url is our URL plus query params, lets split them first.
let [urlPath, urlParams] = req.url.split("?");
// Set our Request Route
if (path[0] === "/" && req.method === "GET") {
if (urlPath === "/" && req.method === "GET") {

if (typeof urlParams !== "string"){
await utils.displayError(req, res, {
code: 400,
msg: "Missing Query Parameters"
});
console.log("Download Returned 400 due to the requested URL having no query parameters");
return;
}

if (urlParams.length > 36){
// Longest valid combo is 36 characters ("os=silicon_mac&type=mac_zip_blockmap")
await utils.displayError(req, res, {
code: 414,
msg: "Requested Parameters are Too Long"
});
console.log("Download Returned 414 due to the provided parameters being too long");
return;
}

let params = {
os: utils.query_os(path[1]),
type: utils.query_type(path[1])
let validatedParams = {
os: utils.query_os(urlParams),
type: utils.query_type(urlParams)
};

if (!params.os || !params.type) {
if (!validatedParams.os || !validatedParams.type) {
await utils.displayError(req, res, {
code: 503,
msg: "Missing Required Download Parameters"
msg: "Required Download Parameters Missing or Invalid"
});
console.log("Download Returned 503 due to missing os or type");
console.log("Download Returned 503 due to missing or invalid os or type");
return;
}

let redirLink = await utils.findLink(params.os, params.type);
let redirLink = await utils.findLink(validatedParams.os, validatedParams.type);

if (!redirLink.ok) {
await utils.displayError(req, res, redirLink);
Expand All @@ -34,7 +63,7 @@ const server = http.createServer(async (req, res) => {
Location: redirLink.content
}).end();

console.log(`Download Returned: OS: ${params.os} - TYPE: ${params.type} - URL: ${redirLink.content}`);
console.log(`Download Returned: OS: ${validatedParams.os} - TYPE: ${validatedParams.type} - URL: ${redirLink.content}`);


} else {
Expand Down

0 comments on commit 007e7a2

Please sign in to comment.