-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
191 lines (174 loc) · 6.2 KB
/
main.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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const express = require('express')
const http = require('http')
const mongo = require('mongodb')
const MongoClient = mongo.MongoClient
const uuid = require('uuid').v4
////////////////////////////////////////////////////////////////////////////////
// Global Constants
////////////////////////////////////////////////////////////////////////////////
const MONGO_URL = 'mongodb://localhost:27017'
const URLS_DB = 'urlsDB'
const URLS = 'urls'
const URLS_COUNT = 'urls.count'
const STATUS_CODE_OK = 200
const STATUS_CODE_BAD_REQUEST = 400
const STATUS_CODE_NOT_FOUND = 404
const STATUS_CODE_INTERNAL_SERVER_ERROR = 500
const STATUS_BAD_REQUEST = 'BAD_REQUEST'
const STATUS_NOT_FOUND = 'NOT_FOUND'
const STATUS_INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR'
const LOG_OPTIONS = {
'color': true,
'depth': null,
}
////////////////////////////////////////////////////////////////////////////////
// Global Variables
////////////////////////////////////////////////////////////////////////////////
var urlsDB
////////////////////////////////////////////////////////////////////////////////
// Helper Functions
////////////////////////////////////////////////////////////////////////////////
const convert = count => {
if (!count) {
return '2'
}
// intentionally excluding '0', '1', 'i', 'l', and 'o'
const character = '23456789abcdefghjkmnpqrstuvwxyz'
var id = ''
while (count) {
id = `${character[count % 31]}${id}`
count = Math.trunc(count / 31)
}
return id
}
////////////////////////////////////////////////////////////////////////////////
// Logging Functions
////////////////////////////////////////////////////////////////////////////////
const logRequest = (id, req) => {
console.dir({
'id': id,
'request': {
'method': req['method'],
'url': req['url'],
'params': req['params'],
'query': req['query'],
'body': req['body']
}
}, LOG_OPTIONS)
}
const logResponse = (id, res, body) => {
console.dir({
'id': id,
'response': {
'statusCode': res['statusCode'],
'statusMessage': res['statusMessage'],
'body': body
}
}, LOG_OPTIONS)
}
////////////////////////////////////////////////////////////////////////////////
// App Configuration
////////////////////////////////////////////////////////////////////////////////
const app = express()
app.use(express.json())
app.set('json spaces', 2)
////////////////////////////////////////////////////////////////////////////////
// REST Methods
////////////////////////////////////////////////////////////////////////////////
// Method: urls.get
app.get('/urls/:resourceId', (req, res) => {
const id = uuid()
logRequest(id, req)
urlsDB.collection(URLS).findOne({
'id': req.params['resourceId'].toLowerCase()
}).then(result => {
if (result) {
const body = {
'id': `${result['id']}`,
'url': `${result['url']}`
}
res.status(STATUS_CODE_OK).json(body)
logResponse(id, res, body)
} else {
const body = {
'error': {
'code': STATUS_CODE_NOT_FOUND,
'message': `Resource ${req.params['resourceId']} was not found.`,
'status': STATUS_NOT_FOUND,
}
}
res.status(STATUS_CODE_NOT_FOUND).json(body)
logResponse(id, res, body)
}
}).catch(error => {
const body = {
'error': {
'code': STATUS_CODE_INTERNAL_SERVER_ERROR,
'message': `Unexpected error occurred when getting resource ${req.params['resourceId']}: ${error.message}`,
'status': STATUS_INTERNAL_SERVER_ERROR
}
}
res.status(STATUS_CODE_INTERNAL_SERVER_ERROR).json(body)
logResponse(id, res, body)
})
})
// Method: urls.insert
app.post('/urls', (req, res) => {
const id = uuid()
logRequest(id, req)
if (!req.body['url'] || !/^https?:\/\/([A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,6}(\/([-a-zA-Z0-9()@:%_\+.~#?&\/=]*))?$/.test(req.body['url'])) {
const body = {
'error': {
'code': STATUS_CODE_BAD_REQUEST,
'message': `Provided URL is not valid: ${req.body['url']}`,
'status': STATUS_BAD_REQUEST,
}
}
res.status(STATUS_CODE_BAD_REQUEST).json(body)
logResponse(id, res, body)
} else {
urlsDB.collection(URLS_COUNT).findOneAndUpdate({
'_id': 'count',
}, {
'$inc': {
'count': 1
}
}).then(result => {
if (result.value) {
return urlsDB.collection(URLS).insertOne({
'id': `${convert(result.value['count'])}`,
'url': req.body['url'],
})
} else { throw new Error('Unable to get urls count') }
}).then(result => {
if (result.insertedCount == 1) {
const body = {
'id': `${result.ops[0]['id']}`,
'url': `${result.ops[0]['url']}`,
}
res.status(STATUS_CODE_OK).json(body)
logResponse(id, res, body)
} else { throw new Error(`Unexpected number of inserted resources: ${result.insertedCount}`) }
}).catch(error => {
const body = {
'error': {
'code': STATUS_CODE_INTERNAL_SERVER_ERROR,
'message': `Unexpected error occurred when inserting resource: ${error.message}`,
'status': STATUS_INTERNAL_SERVER_ERROR,
}
}
res.status(STATUS_CODE_INTERNAL_SERVER_ERROR).json(body)
logResponse(id, res, body)
})
}
})
////////////////////////////////////////////////////////////////////////////////
// Connect
////////////////////////////////////////////////////////////////////////////////
MongoClient.connect(MONGO_URL, { useUnifiedTopology: true }).then(client => {
urlsDB = client.db(URLS_DB)
http.createServer(app).listen(8006)
}).catch(error => {
console.error(error)
process.exit(1)
})