-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin.js
More file actions
100 lines (84 loc) · 2.19 KB
/
Copy pathbin.js
File metadata and controls
100 lines (84 loc) · 2.19 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
const onData = object => chunk => {
console.log('> data > spoling chunk to local memory: ', chunk)
object.data += chunk
}
const onEnd = object => () => console.log('> end > the concatened result of all chunks is: ', object.data)
const onError = error => console.log('> error >', error.message)
const collectDataFromStreamHandler = (stream = null, name = 'DEFAULT') => {
let object = {
data: ''
}
try {
stream
.setEncoding('utf8')
.on('data', onData(object))
.on('end', onEnd(object))
.on('error', onError)
} catch (error) {
console.log('error:', error.message)
throw new Error('invalid stream received')
}
return stream
}
const isValidHTTPMethod = method => {
if (method === 'GET' ||
method === 'POST' ||
method === 'PUT' ||
method === 'DELETE' ||
method === 'PATCH') return
throw new Error('invalid http method')
}
const getEnv = env => {
const method =
typeof process.env.METHOD === 'string' ?
process.env.METHOD : 'GET'
const query =
typeof process.env.QUERY === 'string' ?
process.env.QUERY : ''
const keepAlive =
typeof process.env.KA === 'string' ?
true : false
const keepAliveMsecs =
typeof process.env.KA === 'string' ?
Number.parseInt(process.env.KA) : 0
const body =
typeof process.env.BODY === 'string' ?
Number.parseInt(process.env.BODY) : ''
return {
method,
query,
keepAlive,
keepAliveMsecs,
body
}
}
const response = (req, res, msg = '') => {
let contentType = 'text/plain'
try {
JSON.parse(msg)
contentType = 'application/json'
} catch (error) {
}
res.writeHead(200, {
'Content-Type': contentType
});
res.write(msg)
res.end()
}
const requestLogger = (req, res) => {
console.log('requesting from', req.url)
console.log(`method`, req.method)
}
module.exports = {
server: {
response,
requestLogger
},
universal: {
collectDataFromStreamHandler,
isValidHTTPMethod
},
client: {
getEnv
}
}