repl.it
Express

A hassle free url shortener.

fork
loading
Files
  • index.js
  • static
  • package-lock.json
  • package.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// forked from https://repl.it/@jajoosam/tyni
// see https://repl.it/talk/learn/Build-your-very-own-URL-shortener/9611

// after forking, change the baseUrl on script.js line 2
/* .env should look like this:
TOKEN=708ca41d57c35a9b8c059f9...
*/

const express = require('express');
const app = express();
app.use(express.static('static'));

var jsonstore = require('jsonstore.io') ;
let store = new jsonstore(process.env.TOKEN);

const movedPermanently = 301;
const badRequest = 400;
const notFound = 404;

app.get('/', (req, res) => {
	res.sendFile("static/index.html", {root: __dirname});
});

app.get('/shorten', (req, res) => {
    store.read(req.query.key + "/url").then(url => {
        if (url) {
            res.status(badRequest).json({error: `Error: ${req.query.key} already exists.`});
        } else {
            store.write(req.query.key, {url: req.query.url});
            res.json({status: "OK"});
        }
    });
});

app.get('/:key', (req, res) => {
	store.read(req.params.key + "/url").then(url => {
        if (url) {
    		res.redirect(movedPermanently, url);
        } else {
            res.status(notFound).send(`${req.params.key} not found`);
        }
	});
});

app.listen(3000, () => console.log('server started'));