aboutsummaryrefslogtreecommitdiff
path: root/core/http/client.ts
blob: 6b4e1a3a4b56f059a66fe744d2a6c777043a6c50 (plain)
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
import { InputSentenceProps } from "../../language/types.ts";
import "../../util/array.ts";
import { DeepPartial } from "../../util/types.ts";

import Core from "../api.ts";
import { ConnectionProps, ConnectionPropsDefault } from "./props.ts";
import { CoreRequest, CoreRequestParseSentence, CoreResponseParseSentence } from "./types.ts";

/**
 * @summary HTTP Core client
 * 
 * Connects to an instance of RemoteCoreServer to call Core methods. Handles
 * (de)serialization automatically.
 */
export default class RemoteCoreClient implements Core {
	private props: ConnectionProps;
	ready: Promise<void> = Promise.resolve();

	constructor(options?: ConnectionProps) {
		this.props = { ...ConnectionPropsDefault, ...options };
	}

	private async request(details: CoreRequest) {
		var response = await fetch(`http://${this.props.host}:${this.props.port}`, {
			method: "POST",
			headers: {
				"Accept": "application/json",
				"Content-Type": "application/json",
			},
			body: JSON.stringify(details),
		});
		return response.json();
	}

	async parseSentence(input: string, options?: DeepPartial<InputSentenceProps>) {
		var request: CoreRequestParseSentence = {
			command: "parseSentence",
			options: { input, options, },
		};
		var { response } = await this.request(request) as CoreResponseParseSentence;
		return response;
	}
}