-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.js
84 lines (76 loc) · 2.07 KB
/
convert.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
const configuration = require('./lib/index').default;
function parseMime(str) {
if (/yaml/.test(str)) return 'yaml';
if (/yml/.test(str)) return 'yaml';
if (/ini/.test(str)) return 'ini';
if (/toml/.test(str)) return 'toml';
if (/json/.test(str)) return 'json';
if (/plist/.test(str)) return 'plist';
if (/msgpack/.test(str)) return 'msgpack';
return null;
}
exports.convert = function(event, context, cb) {
const query = event.queryStringParameters || {};
const mimeInput = query.inputType || parseMime(event.headers['Content-Type']);
const mimeOutput = query.outputType || parseMime(event.headers['Accept']);
const inp = event.body;
if (!inp) {
cb(null, {
statusCode: 400,
body: '400 Send some text\n',
});
return;
}
if (!mimeInput || !mimeOutput) {
cb(null, {
statusCode: 400,
body: '400 Specify desired input and output in the query\n(`?outputType=...`/`?inputType=...`)\nor through the Accept/Content-Type headers\n',
});
return;
}
const inputFormat = configuration[mimeInput];
if (!inputFormat) {
cb(null, {
statusCode: 400,
body: `400 Invalid 'inputType' ${mimeInput}, send it with 'content-type' or '?inputType'\n`,
});
return;
}
const outputFormat = configuration[mimeOutput];
if (!outputFormat) {
cb(null, {
statusCode: 400,
body: `400 Invalid 'outputType' ${mimeOutput}, send it with 'accept' or '?outputType'\n`,
});
return;
}
let tmp;
try {
tmp = inputFormat.parse(inp);
} catch (err) {
cb(null, {
statusCode: 422,
body: `422 Failed to parse body as '${mimeInput}':\nError: ${err.message}\n`,
});
return;
}
let body;
try {
body = outputFormat.stringify(tmp);
} catch (err) {
cb(null, {
statusCode: 422,
body: `422 Failed to generate output '${mimeOutput}':\nError: ${err.message}\n`,
});
return;
}
cb(null, {
statusCode: 200,
headers: {
'content-type': `application/${mimeOutput}`,
'x-output-type': mimeOutput,
'x-input-type': mimeInput,
},
body
});
};