-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.js
88 lines (70 loc) · 1.94 KB
/
calc.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
// calc.js
"use strict";
var getUrlForApi;
if (typeof getUrlForApi !== "function") { var { getUrlForApi } = require("./getUrlForApi.js"); };
const str = v => JSON.stringify(v, null, " ");
const paramsFromObject = o => (
o == null
? ""
: typeof URLSearchParams === "function"
? new URLSearchParams(o).toString()
: require("querystring").stringify(o)
);
const calculateFromApi = async (num1, operator, num2, methodAWS) => {
const UNDEF = undefined;
let url = getUrlForApi();
const method = methodAWS.toUpperCase();
const methodAcceptsQSonly = /^(GET|HEAD)$/i;
const bodyObject = {
num1,
operator,
num2
};
let body = null;
let qs = null;
if (methodAcceptsQSonly.test(method)) {
qs = paramsFromObject(bodyObject);
if(qs.length) {
url += "?" + qs;
};
} else {
body = str(bodyObject);
};
const options = {
method: method,
body: body ?? UNDEF,
};
const calculated = await fetch(url, options)
.then(response => {
const { status: statusCode, headers, statusText } = response;
// console.log(Object.fromEntries([...headers]));
return response.json();
})
.then(json => {
const {jsonData, error, details, statusText} = json;
// console.log(statusText, error, details, jsonData);
if(error) {
throw Error(`${statusText}: ${error}`);
};
return jsonData;
})
.catch(err => {
throw err;
});
return calculated;
};
const test = test_event => {
console.log(JSON.stringify(test_event, null, " "));
const { httpMethod, queryStringParameters, body } = test_event;
const { num1, operator, num2 } = body || queryStringParameters || {};
calculateFromApi(num1, operator, num2, httpMethod)
.then(result => {
console.log({ result });
})
.catch(err => {
console.log(err);
});
};
if(typeof exports === "object") {
exports.test = test;
};