forked from busbud/coding-challenge-backend-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateServer.js
188 lines (173 loc) · 5.13 KB
/
createServer.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
const http = require('http')
const url = require("url")
const fs = require('fs')
const { Readable, Writable, Transform } = require('stream')
/**
* Returns true if the url of the requets match the patch
*
* @param {String} path
* @param {IncomingMessage} req
* @returns {Boolean}
*/
const routeIs = (path, req) =>
req.url.indexOf(path) === 0
/**
* Responds a text message.
* Option statusCode is 200 by default
*
* @param {String} text
* @param {ServerResponse} res
* @param {Object} [{statusCode = 200}={}]
*/
const respondText = (text, res, {statusCode = 200} = {}) => {
res.writeHead(statusCode, { 'Content-Type': 'text/plain' })
res.end(text)
}
/**
* Responds a Json.
* Option statusCode is 200 by default
*
* @param {Object} json
* @param {ServerResponse} res
* @param {Object} [{statusCode = 200}={}]
*/
const respondJSon = (json, res, {statusCode = 200} = {}) => {
res.writeHead(statusCode, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(json))
}
/**
*
*
* @param {IncomingMessage} req
* @returns {{q: String, latitude?: Number, longitude?: Number}} parameters
*/
const getSuggestionsParameters = (req) => {
const parsedUrl = url.parse(req.url, true)
const queryAsObject = parsedUrl.query
let qLatitude = parseFloat(queryAsObject.latitude)
let qLongitude = parseFloat(queryAsObject.longitude)
return {
q: queryAsObject.q || '',
latitude: qLatitude > -90 && qLatitude < 90 ?
qLatitude : undefined,
longitude: qLongitude > -180 && qLongitude < 180 ?
qLongitude : undefined
}
}
/**
* Returns the server.
* It takes some dependencies =
* the cities
* the suggest function
*
* @param {{cities: Objecy[], suggest: function}} mainDependencies
* @param {port: Number} options
* @returns {Server}
*/
module.exports = function createServer({cities, suggest}, {port}) {
const httpServer = http.createServer((req, res) => {
if (routeIs('/hello', req)) {
respondText('Hello CI and CD :)', res)
}
else if (routeIs('/index.html', req)) {
fs.createReadStream('./public/index.html').pipe(res)
}
else if (routeIs('/suggestions', req)) {
const params = getSuggestionsParameters(req)
// Validate params
if (params.q.length < 3) {
respondJSon({
error: 'q parameter is required and has to have at least 3 chars'
}, res, {statusCode: 400})
return
}
const response = {
suggestions: suggest(cities, params.q,params.latitude, params.longitude)
// format the suggestions
.map(city => ({
name: [city.name, city.adminCode1, city.countryCode].join(', '),
latitude: city.latitude,
longitude: city.longitude,
score: city.score
}))
}
response.suggestions.length === 0 ?
respondJSon(response, res, {statusCode: 404}) :
respondJSon(response, res, {statusCode: 200})
}
else if (routeIs('/streamsuggestions', req)) {
// stream playground :)
const getParams = new Transform({
readableObjectMode: true,
transform(chunk, encoding, callback) {
const url = chunk.toString()
const params = getSuggestionsParameters({url})
this.push(
params
)
callback()
}
})
const validateParams = new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform(params, encoding, callback) {
if (params.q.length < 3) {
this.push(null)
callback(new Error('q'))
return
}
this.push(params)
callback()
}
})
const getSuggestions = new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform(params, encoding, callback) {
const suggestions = suggest(cities, params.q,params.latitude, params.longitude)
// format the suggestions
.map(city => ({
name: [city.name, city.adminCode1, city.countryCode].join(', '),
latitude: city.latitude,
longitude: city.longitude,
score: city.score
}))
this.push(suggestions)
callback()
}
})
const respond = new Writable({
objectMode: true,
write(suggestions, encoding, callback) {
suggestions.length === 0 ?
respondJSon({suggestions}, res, {statusCode: 404}) :
respondJSon({suggestions}, res, {statusCode: 200})
callback()
}
})
const inStream = new Readable({
read(size) {
this.push(null)
}
})
inStream
.pipe(getParams)
.pipe(validateParams)
.on('error', (err) => {
respondJSon({
error: 'q parameter is required and has to have at least 3 chars'
}, res, {statusCode: 400})
})
.pipe(getSuggestions)
.pipe(respond)
inStream.push(req.url)
}
else {
respondText('Not found :/', res, {statusCode: 404})
}
})
httpServer.listen(port, '0.0.0.0')
console.log(`Listening at :${port}`)
return httpServer
}