-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathput-request.js
More file actions
63 lines (55 loc) · 1.38 KB
/
put-request.js
File metadata and controls
63 lines (55 loc) · 1.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
const https = require('https');
function putRequest(path, body) {
const options = {
hostname: 'reqres.in',
// 👇 specify path e.g. /api/users/2
path: path,
method: 'PUT',
port: 443, // 👈️ replace with 80 for HTTP requests
headers: {
'Content-Type': 'application/json',
},
};
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (err) {
reject(new Error(err));
}
});
});
req.on('error', err => {
reject(new Error(err));
});
// 👇️ write body on request object
req.write(JSON.stringify(body));
req.end();
});
}
exports.handler = async event => {
try {
const result = await putRequest(`/api/users/2`, {
name: 'Bob Jones',
job: 'accountant',
});
console.log('result is: 👉️', result);
// 👇️️ response structure assume you use proxy integration with API gateway
return {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(result),
};
} catch (error) {
console.log('Error is: 👉️', error);
return {
statusCode: 400,
body: error.message,
};
}
};