aboutsummaryrefslogtreecommitdiff
path: root/core/http/client.ts
blob: 80f77b3d39494cb7284c39dad441e8816ec4755e (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import "../../util/array.ts";

import Core, { CoreExport, CoreImport, CoreSearch, CoreUser } from "../api.ts";
import { ConnectionProps, ConnectionPropsDefault } from "./props.ts";
import { CoreRequest, CoreRequestSearchSentence, CoreRequestSearchTerms, CoreResponseSearchSentence, CoreResponseSearchTerms } 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 {
	public ready: Promise<void> = Promise.resolve();

	private props: ConnectionProps;

	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();
	}

	public search: CoreSearch = {
		terms: async term => {
      var request: CoreRequestSearchTerms = {
        command: "search.terms",
        options: { term, },
      };
      var { response } = await this.request(request) as CoreResponseSearchTerms;
      return response;
		},
		sentence: async (sentence, optional?) => {
      var request: CoreRequestSearchSentence = {
        command: "search.sentence",
        options: { sentence, optional, },
      };
      var { response } = await this.request(request) as CoreResponseSearchSentence;
      return response;
		},
	};

	public user: CoreUser = {};

	public import: CoreImport = {};

	public export: CoreExport = {};
}