forked from freeCodeCamp/boilerplate-project-urlshortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (53 loc) · 1.86 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const UrlValidator = require('./urlvalidator.js');
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dns = require('dns');
const mongoUri = process.env['MONGO_URI']
// Data Base Configuration
mongoose.connect(mongoUri);
const { Schema } = mongoose;
const shortUrlSchema = new Schema({
url: String, // String is shorthand for {type: String}
});
const ShortUrl = mongoose.model('ShortUrl', shortUrlSchema);
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.use(bodyParser.urlencoded({extended: false})); // parse post body
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
// Your first API endpoint
app.get('/api/hello', function(req, res) {
res.json({ greeting: 'hello API' });
});
app.post('/api/shorturl', (req, res) => {
if(!new UrlValidator().test(req.body.url))
return res.json({error : 'invalid url'});
let domain = new UrlValidator().getDomain(req.body.url);
dns.lookup(domain, {all : true}, (err, addresses) => {
if(err)
return res.json({error : 'invalid url'});
else{
const shortUrl = new ShortUrl({url: req.body.url});
shortUrl.save().then(urlSaved => res.json({ original_url: req.body.url, short_url: urlSaved._id}));
}
});
});
app.get('/api/shorturl/:shorturl', (req, res) => {
if(!req.params.shorturl)
return res.json({error : 'invalid url'});
ShortUrl.findById(req.params.shorturl).exec((err, url) => {
if(!err && url)
return res.redirect(url.url);
return res.json({error : 'invalid url'});
});
});
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});