-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.ts
79 lines (66 loc) · 2.38 KB
/
api.ts
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
import {RoomEvent, Player, Room, Action} from './model'
class BackendApi {
constructor(readonly url: string,
readonly listener: (event: RoomEvent) => void) {}
private handle<T>(res: Response): Promise<T> {
if (res.ok) {
return res.json();
} else {
return res.text()
.then(msg => Promise.reject(msg));
}
}
private getJson<T>(uri: string): Promise<T> {
return fetch(this.url + uri)
.then(res => this.handle<T>(res));
};
private postJson<T>(uri: string, json: any): Promise<T> {
const request: RequestInit = {
method: 'POST',
body: JSON.stringify(json)
};
return fetch(this.url + uri, request)
.then(res => this.handle<T>(res));
};
private registerWS(roomId: number, playerId: string) {
const wsUrl = this.url.replace('http://', 'ws://');
const ws = new WebSocket(wsUrl + `/ws/${roomId}`);
// Register events
ws.onopen = () => {
console.debug('WS open', roomId);
// Register to room
ws.send(JSON.stringify({playerId}));
};
ws.onmessage = (event: MessageEvent) => {
console.debug('WS message', event.data);
const roomEvent = JSON.parse(event.data) as RoomEvent;
this.listener(roomEvent);
};
ws.onclose = () => console.info('WS close');
ws.onerror = (event: Event) => console.error('WS error', event);
}
// Auth
login(name: string): Promise<Player> {
return this.postJson('/api/auth/login', {name});
}
logout(playerId: string): Promise<Player> {
return this.postJson('/api/auth/logout', {playerId});
}
// Room
getRooms(): Promise<Room[]> {
return this.getJson('/api/room');
}
join(roomId: number, playerId: string): Promise<Room> {
return this.postJson<Room>('/api/room/join', {roomId, playerId})
.then(room => {
this.registerWS(roomId, playerId);
return room;
});
}
leave(roomId: number, playerId: string): Promise<Room> {
return this.postJson('/api/room/leave', {roomId, playerId})
}
action(roomId: number, playerId: string, action: Action): Promise<Room> {
return this.postJson('/api/room/move', {roomId, playerId, action})
}
}