forked from JaylyDev/ScriptAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
201 lines (170 loc) · 6.48 KB
/
index.ts
File metadata and controls
201 lines (170 loc) · 6.48 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Script example for ScriptAPI
// Author: Jayly <https://github.com/JaylyDev>
// Project: https://github.com/JaylyDev/ScriptAPI
import { ScoreboardObjective, world } from '@minecraft/server';
import { b64_to_utf8, utf8_to_b64 } from './encoding';
declare global {
var KEY: string;
};
const overworld = world.getDimension('overworld');
export class RESTError extends Error { };
interface RequestOptions {
[RequestMethod.DELETE]: {
request: { key?: string; };
response: void;
};
[RequestMethod.GET]: {
request: { key: string; };
response: string | number | boolean;
};
[RequestMethod.PUT]: {
request: { key: string; value: string | number | boolean; };
response: void;
};
[RequestMethod.POST]: {
request: {};
response: void;
};
[RequestMethod.PATCH]: {
request: { key: string; value: string | number | boolean; };
response: number | void;
};
};
type RequestOption<T extends keyof RequestOptions> = {
method: T;
} & RequestOptions[T]['request'];
globalThis.KEY = 'jayly-restful';
export class Table {
readonly route: `/${string}`;
readonly data: Member[];
/**
* @internal
*/
toRawtext() {
const rawData = JSON.stringify({ route: this.route, data: this.data });
return utf8_to_b64(rawData);
};
constructor(rawtext: string) {
try {
const { route, data } = JSON.parse(b64_to_utf8(rawtext));
this.route = route;
this.data = data;
} catch (error) {
const { route, data } = JSON.parse(rawtext);
this.route = route;
this.data = data;
}
};
};
export class Member {
key: string;
value: string | number | boolean;
constructor(key: string, value: string | number | boolean) {
this.key = key;
this.value = value;
};
};
/**
* Request methods available with Rest API
*/
export enum RequestMethod {
/**
* POST requests are commonly used to create a new resource that is a
* subordinate of the specified route.
*/
POST = 'POST',
/**
* GET requests are commonly used to retrieve information about a resource
* at the specified route.
*/
GET = 'GET',
/**
* PUT requests are commonly used to update a single resource that already
* exists in a resource collection.
*/
PUT = 'PUT',
/**
* PATCH requests are commonly used to update partial of an already
* existed resource collection.
*/
PATCH = 'PATCH',
/**
* POST requests are commonly used to remove an existing resource that is a
* subordinate of the specified route.
*/
DELETE = 'DELETE',
};
export class REST {
private readonly scoreboard: ScoreboardObjective;
constructor(id: string) {
const regex = /^[a-z]+$/;
if (!regex.test(id)) throw new RESTError('Invalid id.');
const objectiveId = id;
this.scoreboard = world.scoreboard.getObjective(objectiveId) ?? world.scoreboard.addObjective(objectiveId, id);
};
request<T extends keyof RequestOptions>(route: `/${string}`, options: RequestOption<T>): RequestOptions[T]["response"] {
const participant = this.scoreboard.getParticipants().find((value) => new Table(value.displayName).route === route);
// delete route
if (options.method === RequestMethod.DELETE) {
if (!participant) throw new RESTError('Route not found.');
const parsedOption = options as RequestOption<RequestMethod.DELETE>;
if (typeof parsedOption.key !== 'string') this.scoreboard.removeParticipant(participant);
else {
const table = new Table(participant.displayName);
const memberIndex = table.data.findIndex((value) => value.key === parsedOption.key);
if (memberIndex === -1) throw new RESTError('Member not found in route ' + route);
// set value
table.data.splice(memberIndex, 1);
const encrypted = table.toRawtext();
// version increment
const version = this.scoreboard.getScore(participant);
overworld.runCommand(`scoreboard players set ${JSON.stringify(encrypted)} ${JSON.stringify(this.scoreboard.id)} ${version + 1}`);
};
}
// get member value from route
else if (options.method === RequestMethod.GET) {
const parsedOption = options as RequestOption<RequestMethod.GET>;
if (!participant) throw new RESTError('Route not found.');
const { data: members } = new Table(participant.displayName);
const data = members.find((v) => v.key === parsedOption.key);
if (!data) throw new RESTError('Member not found in route ' + route);
return data.value;
}
// modify member value from route
else if (options.method === RequestMethod.PATCH) {
const parsedOption = options as RequestOption<RequestMethod.PATCH>;
if (!participant) throw new RESTError('Route not found.');
const table = new Table(participant.displayName);
const member = table.data.find((value) => value.key === parsedOption.key);
if (!member) throw new RESTError('Member not found in route ' + route);
// set value
member.value = parsedOption.value;
const encrypted = table.toRawtext();
// version increment
const version = this.scoreboard.getScore(participant);
overworld.runCommand(`scoreboard players set ${JSON.stringify(encrypted)} ${JSON.stringify(this.scoreboard.id)} ${version + 1}`);
return version + 1;
}
// create a new route
else if (options.method === RequestMethod.POST) {
if (!!participant) throw new RESTError('Cannot create new route. Route ' + JSON.stringify(route) + ' already exists.');
const rawtext = JSON.stringify({ route, data: [] });
const table = new Table(rawtext.toString());
overworld.runCommand(`scoreboard players set ${JSON.stringify(table.toRawtext())} ${JSON.stringify(this.scoreboard.id)} 1`);
}
// create a new member from route
else if (options.method === RequestMethod.PUT) {
const parsedOption = options as RequestOption<RequestMethod.PUT>;
if (!participant) throw new RESTError('Route not found.');
const table = new Table(participant.displayName);
if (table.data.findIndex((value) => value.key === parsedOption.key) > -1) throw new RESTError('Member exist in route ' + route);
// set value
const member = new Member(parsedOption.key, parsedOption.value);
table.data.push(member);
const encrypted = table.toRawtext();
// version increment
overworld.runCommand(`scoreboard players set ${JSON.stringify(encrypted)} ${JSON.stringify(this.scoreboard.id)} 1`);
}
else throw new RESTError('Request method ' + options.method + ' not acceptable.');
};
};