forked from REI-Team/NodeJS-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
post.js
60 lines (56 loc) · 2.49 KB
/
post.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
'use strict'
const url = require('url')
class Obj {
// Agafa les dades que arriben d'una crida POST i retorna un objecte JSON
static getPostObject (request) {
return new Promise(async (resolve, reject) => {
let body = '',
error = null
request.on('data', (data) => { body = body + data.toString() })
request.on('close', () => { /* TODO - Client closed connection, destroy everything! */ })
request.on('error', (err) => { error = 'Error getting data' })
request.on('end', async () => {
let rst = null
if (error !== null) {
console.log('Error getting data from post: ', error)
return reject(error)
} else {
try {
let params;
let objPost;
if (body.charAt(0) == '{') {
// POST from AJAX
try {
objPost = JSON.parse(body)
} catch (e) {
console.log('Error parsing JSON from: ', body)
}
} else {
// POST from form
params = new URLSearchParams(body)
objPost = Object.fromEntries(params)
}
let keys = Object.keys(objPost)
for (let cnt = 0; cnt < keys.length; cnt = cnt + 1) {
let value = objPost[keys[cnt]]
if (!isNaN(value)) { // Check if is a number (example: "2ABC" is not a 2)
let valueInt = parseInt(value)
let valueFlt = parseFloat(value)
if (valueInt && valueFlt) {
if (valueInt == valueFlt) objPost[keys[cnt]] = valueInt
else objPost[keys[cnt]] = valueFlt
}
}
}
return resolve(objPost)
} catch (e) {
console.log('Error parsing data from post: ', error)
return reject(e)
}
}
})
})
}
}
// Export
module.exports = Obj