aboutsummaryrefslogtreecommitdiff
path: root/src/zenserver/frontend/html/util/fetcher.js
blob: 45f5974046a49f191563abd3e9d43ef9986c368c (plain) (blame)
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
// Copyright Epic Games, Inc. All Rights Reserved.

"use strict";

import { CbObject } from "./compactbinary.js"

////////////////////////////////////////////////////////////////////////////////
export class Fetcher
{
	constructor()
	{
		this._resource = "";
		this._query = {};
	}

	resource(...parts)
	{
		var value = parts.join("/");
		if (!value.startsWith("/"))
			value= "/" + value;
		this._resource = value;
		return this;
	}

	param(name, value)
	{
		this._query[name] = value;
		return this;
	}

	async json()
	{
		const response = await this._get("application/json");
		return response ? (await response.json()) : {};
	}

	async cbo()
	{
		const response = await this._get("application/x-ue-cb");
		if (!response)
			return null;

		const buffer = await response.arrayBuffer();
		const data = new Uint8Array(buffer);
		return new CbObject(data);
	}

	async delete()
	{
		const resource = this._build_uri();
		const response = await fetch(resource, { "method" : "DELETE" });
	}

	_build_uri()
	{
		var suffix = "";
		for (var key in this._query)
		{
			suffix += suffix ? "&" : "?";
			suffix += key + "=" + this._query[key];
		}
		return this._resource + suffix;
	}

	async _get(accept="*")
	{
		const resource = this._build_uri();
		const response = await fetch(resource, {
			"method" : "GET",
			"headers" : { "Accept": accept },
		});

		if (response.status >= 200 && response.status <= 299)
			return response;
	}
}