| 123456789101112131415161718192021222324252627282930313233343536 |
- /*---
- title: Serverless endpoint
- group: Request modes
- summary: A script on user:/ reads the method, query and body like an API endpoint.
- path: user:/Scripts/api.agi
- setup: {"request":{"method":"POST","query":{"format":"long"},"json":{"items":[3,5,8]}}}
- ---*/
- /*
- Scripts saved on user:/ or tmp:/ run like a serverless endpoint: there
- are no POST globals, but getPara (query), postPara (form fields) and
- readBody (raw body) instead. Relative paths start at the script's folder.
- */
- requirelib("filelib");
- var format = getPara("format") || "long";
- var items = [];
- try {
- items = JSON.parse(readBody()).items || [];
- } catch (e) {
- sendJSONResp({ error: "the body must be JSON" });
- exit();
- }
- var sum = 0;
- for (var i = 0; i < items.length; i++) {
- sum += items[i];
- }
- // A relative path: user:/Scripts/last-result.txt
- filelib.writeFile("last-result.txt", String(sum));
- if (format === "short") {
- sendResp(String(sum));
- } else {
- sendJSONResp({ method: REQ_METHOD, items: items, sum: sum });
- }
|