-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser_api.ts
More file actions
79 lines (78 loc) · 2.44 KB
/
browser_api.ts
File metadata and controls
79 lines (78 loc) · 2.44 KB
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
import { apiPort, DatasetApiClient } from "./deps.ts";
import { apiPathParse } from "./utils.ts";
import { renderJSON } from "./render.ts";
/**
* handleBrowserAPI implements the browser accessible API represented in COLD.
* It is a read API only and responses are always in JSON.
*/
export async function handleBrowserAPI(
req: Request,
options: { debug: boolean; htdocs: string; baseUrl: string; apiUrl: string },
): Promise<Response> {
if (req.method !== "GET") {
return renderJSON({
"ok": false,
"msg": `${req.method} method not supported`,
}, 501);
}
let basePath: string = "";
try {
basePath = new URL(options.baseUrl).pathname.replace(/\/$/, "");
} catch {
basePath = "";
}
const apiReq: { [key: string]: string } = apiPathParse(req.url, basePath);
if (apiReq.c_name === undefined) {
return renderJSON({
"ok": false,
"msg": `${apiReq.c_name} collection not found`,
}, 404);
}
if (apiReq.query_name === undefined) {
return renderJSON({
"ok": false,
"msg": `${apiReq.query_name} query not found`,
}, 404);
}
let ds = new DatasetApiClient(apiPort, apiReq.c_name);
// NOTE: We have more than FIXME: Need to pass in the parameter value(s)
let qObj: { [key: string]: string } = {};
let body: string = "";
let pList: string[] = [];
if (apiReq.query_name === "lookup_clgid") {
body = JSON.stringify({ name: apiReq.q, alternative: apiReq.q });
pList = ["name", "alternative"];
} else {
for (let k of Object.keys(apiReq)) {
if (k !== "query_name" && k !== "c_name") {
if (apiReq.hasOwnProperty(k)) {
// handle special case for alternative name search ..., pre-paramaterized requests
const v = apiReq[k];
qObj[k] = v;
pList.push(k);
}
}
}
body = JSON.stringify(qObj);
}
let resp = await ds.query(apiReq.query_name, pList, body);
if (resp.ok) {
try {
let data = await resp.json();
return renderJSON(data, 200);
} catch (err) {
return renderJSON({
"ok": false,
"msg": `query ${apiReq.query_name} failed to read response: ${err}`,
"api": apiReq,
}, 500);
}
}
// Consume the error body to avoid corrupting the keep-alive connection
await resp.body?.cancel();
return renderJSON({
"ok": false,
"msg": `query ${apiReq.query_name} failed with status ${resp.status}`,
"api": apiReq,
}, resp.status === 404 ? 404 : 500);
}