-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
103 lines (91 loc) · 2.84 KB
/
app.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
const util = require('util');
const FormData = require('form-data');
const axios = require('axios');
const busboy = require('async-busboy');
const fs = require('fs');
const Busboy = require("busboy");
const parseFormData = (event) => {
return new Promise((resolve, reject) => {
const busboy = new Busboy({
headers: {
...event.headers,
"content-type":
event.headers["Content-Type"] || event.headers["content-type"],
},
});
const result = {
files: [],
};
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
file.on("data", (data) => {
result.files.push({
file: data,
fileName: filename,
contentType: mimetype,
});
});
});
busboy.on("field", (fieldname, value) => {
try {
result[fieldname] = JSON.parse(value);
} catch (err) {
result[fieldname] = value;
}
});
busboy.on("error", (error) => reject(`Parse error: ${error}`));
busboy.on("finish", () => {
event.body = result;
resolve(event);
});
busboy.write(event.body, event.isBase64Encoded ? "base64" : "binary");
busboy.end();
});
};
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
exports.helloWorld = async (req, res) => {
console.log("lambda");
try {
await parseFormData(req);
var form = new FormData();
for (var i = 0; i < req.body.files; ++i) {
var file = req.body.files[i];
console.log(file);
}
delete req.body.files;
Object.keys(req.body).forEach((key, index) => {
var val = req.body[key];
form.append(key, val);
console.log(key, val);
})
try {
var options = {
method: 'post',
url: 'https://api.remove.bg/v1.0/removebg',
headers: {
'accept': 'image/*',
'X-API-Key': process.env.REMOVEBG_API_KEY,
'Content-Type': 'application/x-www-form-urlencoded',
...form.getHeaders()
},
data: form,
responseType: "arraybuffer"
};
var axiosResponse = await axios(options);
res.status(axiosResponse.status).set('content-type', axiosResponse.headers['content-type']).send(axiosResponse.data);
//var response = { statusCode: axiosResponse.status, body: axiosResponse.data, headers: {'content-type': axiosResponse.headers['content-type']} };
//return(response);
} catch (error) {
var msg = error.message ? error.messsage : error.response.data.errors[0].detail;
console.log(msg);
return ({ statusCode: error.status ? error.status : 500, body: JSON.stringify({ message: msg }) });
}
} catch (err) {
console.log(err.message);
return ({ statusCode: 500, body: JSON.stringify({ message: err }) });
}
};