-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
151 lines (132 loc) · 3.38 KB
/
api.js
File metadata and controls
151 lines (132 loc) · 3.38 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUI = require('swagger-ui-express');
const ShortURL = require('./src/models/url');
const cors = require('cors');
const _ = require('lodash');
app.use([express.urlencoded({ extended: false }), cors()]);
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'URL Shortner API',
version: '1.0.0'
}
},
apis: ['api.js'],
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs));
const validURL = function (str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}
/**
* @swagger
* /:
* get:
* description: Get all URLs
* responses:
* 200:
* description: Success
*/
app.get('/', async (req, res) => {
const allData = await ShortURL.find();
res.json(allData);
});
app.get('/short', async (req, res) => {
// insert the record using the model
const record = new ShortURL({
full: 'test'
});
await record.save();
const data = {
fullUrl: record.full,
short: record.short
};
res.json(data);
});
/**
* @swagger
* /short:
* post:
* description: Create a new shortened URL
* parameters:
* - name: fullUrl
* description: The URL to shorten
* in: query
* required: true
* type: string
* responses:
* 201:
* description: Created
*/
app.post('/short', async (req, res) => {
const fullUrl = req.query.fullUrl
console.log('URL requested: ', fullUrl);
const valid = validURL(fullUrl);
if(!valid && fullUrl.length < 10) {
res.json({error: "Invalid URL"});
}
else {
let record = await ShortURL.findOne({ full: fullUrl })
if (_.isNil(record)) {
// insert the record using the model
record = new ShortURL({
full: fullUrl
});
await record.save();
}
const data = {
fullUrl: fullUrl,
short: record.short
};
res.json(data);
}
});
/**
* @swagger
* /{shortid}:
* get:
* description: Get a short URL's original URL
* parameters:
* - name: shortid
* description: The ID of the short URL
* in: path
* required: true
* type: string
* responses:
* 302:
* description: Success
*/
app.get('/:shortid', async (req, res) => {
// grab the :shortid param
debugger;
const shortid = req.params.shortid;
// perform the mongoose call to find the long URL
const rec = await ShortURL.findOne({ short: shortid });
// if null, set status to 404 (res.sendStatus(404))
if (!rec) return res.sendStatus(404);
// if not null, increment the click count in database
rec.clicks++;
await rec.save();
// redirect the user to original link
res.redirect(rec.full);
});
// Setup your mongodb connection here
mongoose.connect('mongodb+srv://dbUser:dbPass@cluster0.4qc2z.mongodb.net/url_shortner?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true
})
mongoose.connection.on('open', () => {
// Wait for mongodb connection before server starts
app.listen(5000, () => {
console.log("API server started on port 5000");
});
})