Skip to content

Instantly share code, notes, and snippets.

@danprince
Last active July 13, 2016 13:29
Show Gist options
  • Save danprince/1bdd9375caf5c14e303a1540ec172389 to your computer and use it in GitHub Desktop.
Save danprince/1bdd9375caf5c14e303a1540ec172389 to your computer and use it in GitHub Desktop.
WebTask URL Shortner
node_modules
_app.js
*.log
const routes = {
error(req, res, err) {
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end(`
<h1>Error</h1>
<p>I'm afraid something went wrong!</p>
<pre>${err}</pre>
`);
},
success(req, res, key) {
const { host } = req.headers;
const path = req.url.split('?')[0];
const url = `${host}${path}${key}`;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<h1>Success</h1>
<a href=${url}>${url}</a>
`);
},
redirect(req, res, url) {
res.writeHead(301, { 'Location': url });
res.end();
}
};
function generateUniqueKey(object) {
const key = Math.random().toString(36).slice(2);
if(object.hasOwnProperty(key)) {
return generateUniqueKey(object);
} else {
return key;
}
}
module.exports = function(ctx, req, res) {
const { storage, data } = ctx;
storage.get((err, redirects={}) => {
if(err) return routes.error(req, res, err);
const shouldShorten = data.hasOwnProperty('url');
if(shouldShorten) {
const key = generateUniqueKey(redirects);
const url = decodeURIComponent(data.url);
redirects[key] = url;
storage.set(redirects);
return routes.success(req, res, key);
} else {
const key = req.url.split('/').slice(-1)[0];
const url = redirects[key];
return routes.redirect(req, res, url);
}
});
}
{
"name": "wt-url",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "wt ls",
"predeploy": "buble app.js > _app.js",
"deploy": "wt create _app.js",
"postdeploy": "rm _app.js",
"postinstall": "wt init"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"buble": "^0.12.5",
"wt-cli": "^3.3.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment