Create the API and management

This commit is contained in:
buzzcode2007 2025-03-23 07:48:47 +00:00
parent 02709cccf4
commit 31e074a5a8
3 changed files with 213 additions and 0 deletions

95
scripts/API.js Executable file
View file

@ -0,0 +1,95 @@
// Import modules
var URLManage = require(`./database/URLs`).URLManage;
var Messaging = require(`./utilities/messaging`).Messaging;
const bodyParser = require('body-parser');
class ShortenAPI {
/*
Paths used by this API.
*/
#paths = {
"create": ["/api/shorturl"],
"access": ["/:ID", "/api/shorturl/:ID"]
}
/*
Create the URL shortener parser API.
@param {Express} INSTANCE - The Express instance
*/
constructor (INSTANCE) {
this[`instance`] = INSTANCE;
this[`instance`].use(bodyParser.json());
this[`instance`].use(bodyParser.urlencoded({extended: true}));
this[`management`] = new URLManage;
this.prepareRedirect();
this.startCreation();
}
/*
Redirect from the short link.
*/
prepareRedirect() {
const findRedirect = (REQUEST, RESPONSE) => {
const redirectBrowser = (URL) => {
return((URL) ? RESPONSE.redirect(URL) : null);
}
try {
((Object.keys(REQUEST.params).length)
? REQUEST.params.ID
: false) ?
this[`management`].open(REQUEST.params.ID, redirectBrowser)
: false;
} catch(ERR) {
Messaging.exception(RESPONSE, ERR);
}
};
this.#paths[`access`].forEach((PATH) => {
this[`instance`].get(PATH, findRedirect)
console.log(`Redirection ready on ${PATH}.`);
});
}
/*
Enable receiving requests.
*/
startCreation() {
const redirect = (REQUEST, RESPONSE) => {
try {
let QUERY = {};
if ((REQUEST.body) ? Object.keys(REQUEST.body).length : false) {
QUERY = REQUEST.body;
} else if ((REQUEST.query) ? Object.keys(REQUEST.query).length : false) {
QUERY = REQUEST.query;
}
let RESULT = {};
RESULT[`original_url`] = QUERY[`url`];
const sendRedirect = (HASH) => {
RESULT[`short_url`] = HASH;
RESPONSE.json(RESULT);
}
this[`management`].create(RESULT[`original_url`], sendRedirect);
} catch(ERR) {
Messaging.exception(RESPONSE, ERR);
};
};
[`get`, `post`].forEach((METHOD) => {
this.#paths[`create`].forEach((PATH) => {
this[`instance`][METHOD](PATH, redirect);
console.log(`Creation ready on ${PATH} for method ${METHOD}.`)
});
})
}
}
module.exports = {ShortenAPI};