-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
102 lines (91 loc) · 3.18 KB
/
index.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
const FormData = require('form-data');
const axios = require('axios');
const Busboy = require("busboy");
require('dotenv').config();
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({
fieldname: fieldname,
encoding: encoding,
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.removebg = async (req, res) => {
try {
await parseFormData(req);
var form = new FormData();
for (var i = 0; i < req.body.files.length; ++i) {
var file = req.body.files[i];
form.append(file.fieldname, file.file, file.fileName);
}
delete req.body.files;
Object.keys(req.body).forEach((key, index) => {
var val = req.body[key];
form.append(key, val.toString());
})
try {
var options = {
method: 'post',
url: 'https://api.remove.bg/v1.0/removebg',
headers: {
'accept': 'image/*',
'X-API-Key': process.env.REMOVE_BG_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);
} catch (error) {
var errorResponse = { title: error.message };
if (error.response && error.response.data) {
var errorResponse = JSON.parse(error.response.data);
if (errorResponse.errors && errorResponse.errors[0]) {
errorResponse = errorResponse.errors[0];
}
}
res.status(500).send(errorResponse);
}
} catch (error) {
res.status(500).send({ title: error.message });
}
};