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
|
import { serve } from "https://deno.land/std@0.192.0/http/server.ts";
import "../../util/string.ts";
import RawCore from "../raw/api.ts";
import { ConnectionProps, ConnectionPropsDefault } from "./props.ts";
import { CoreRequest, CoreRequestSearchSentence, CoreRequestSearchTerms, CoreRequestUserTermPriority, CoreResponseSearchSentence, CoreResponseSearchTerms, CoreResponseUserTermPriority } from "./types.ts";
export default class RemoteCoreServer extends RawCore {
private props: ConnectionProps;
private handlers: Record<string, (req: CoreRequest) => Promise<Response>> = {
"search.terms": async _req => {
var req = _req as CoreRequestSearchTerms;
var term = req.options?.term;
if (!term) return new Response("", { status: 404 });
return new Response(JSON.stringify({
response: await this.search.terms(term),
} as CoreResponseSearchTerms));
},
"search.sentence": async _req => {
var req = _req as CoreRequestSearchSentence;
var sentence = req.options?.sentence
var optional = req.options?.optional;
if (!sentence) return new Response("", { status: 404 });
return new Response(JSON.stringify({
response: await this.search.sentence(sentence, optional),
} as CoreResponseSearchSentence));
},
"user.termPriority": async _req => {
var req = _req as CoreRequestUserTermPriority;
var ok = true;
ok = ok && (typeof req.options?.userID === "number");
ok = ok && !!(req.options?.expression);
ok = ok && !!(req.options?.reading);
ok = ok && (typeof req.options?.priority === "number");
if (!ok) return new Response("", { status: 404 });
await this.user.termPriority(req.options!.userID, req.options!.expression, req.options!.reading, req.options!.priority);
return new Response(JSON.stringify({} as CoreResponseUserTermPriority));
},
};
constructor(options?: ConnectionProps) {
super();
this.props = { ...ConnectionPropsDefault, ...options };
}
async start() {
serve(async (req) => {
if (req.method != "POST") return new Response("", { status: 400 }); // wrong request (not post)
var request = (await req.text()).json({}) as CoreRequest;
if (!request.command) return new Response("", { status: 400 }); // wrong request (no command)
var handler = this.handlers[request.command];
if (!handler) return new Response("", { status: 404 }); // not found (unknown command)
return await handler(request);
}, {
port: this.props.port,
onListen: () => { }
});
}
}
|