const Mongoose = require(`mongoose`); const DBManagement = require(`./management`).DBManagement; const URLs = require(`../utilities/URLs`).URLs; const CustomErrors = require(`../utilities/errors`).CustomErrors; const HashTools = require(`../utilities/hash`).HashTools; class URLManage extends DBManagement { /* Begin the URL management and connection. */ constructor () { super(`localhost:27017`); this.schema = new Mongoose.Schema({ "original": {"type": String, "required": true}, "shortened": {"type": String, "required": true} }); this[`state`].then(() => {this.model = this[`connection`].model(`URL`, this[`schema`]);}) }; /* Open the original URL given an identifier. @param {string} ID the ID @param {function} done the callback function when successful @return {string} the original URL */ open (ID, done) { this.state.then(() => { this.model.findOne({"shortened": ID}).then((DATA) => { console.log((DATA) ? `Lengthened shortened URL with ID ${ID} to ${DATA[`original`]}.` : `No shortened URL with ID ${ID}.`); return done((DATA) ? DATA[`original`] : null); }).catch((ERR) => { throw ERR; }) }).catch((ERROR) => {throw new CustomErrors.DBProblem(ERROR.message)}); }; /* Search for a short link given a URL. @param {string} URL the URL to shorten @param {function} done the callback function when successful @return {string} ID the ID */ search(URL, done) { // Throw an error for an incorrect URL. if (!URLs.test(URL)) { throw new CustomErrors.URL(null, URL); }; this.state.then(() => { this.model.findOne({"original": URL}).then((DATA) => { console.log((DATA) ? `The ID ${DATA[`shortened`]} refers to ${URL}.` : `No ID pertains to ${URL}.`); return done((DATA) ? DATA[`shortened`] : null); }).catch((ERR) => { throw ERR; }); }).catch((ERROR) => {throw new CustomErrors.DBProblem(ERROR.message)}) }; /* Shorten the URL. @param {string} URL the URL to shorten @param {function} done the callback function @return {string} ID the ID */ create(URL, done) { // Throw an error for an incorrect URL. if (!URLs.test(URL)) { throw new CustomErrors.URL(null, URL); }; let ENTRY = {"original": URL}; const save = (ID) => { (ID) ? done(ID) : HashTools.digest(URL, {"output": "Number"}).then((HASH) => { ENTRY[`shortened`] = HASH; let DOCUMENT = new this.model(ENTRY); this.state.then(() => { DOCUMENT.save().then((DATA) => {done(HASH)}).catch((ERR) => {throw ERR;}) }).catch((ERROR) => {throw new CustomErrors.DBProblem(ERROR.message)}); }); } this.search((ENTRY[`original`]), save); } } module.exports = {URLManage};