-
Notifications
You must be signed in to change notification settings - Fork 43
/
match_rpc.ts
65 lines (57 loc) · 2.12 KB
/
match_rpc.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
// Copyright 2020 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
let rpcFindMatch: nkruntime.RpcFunction = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, payload: string): string {
if (!ctx.userId) {
throw Error('No user ID in context');
}
if (!payload) {
throw Error('Expects payload.');
}
let request = {} as RpcFindMatchRequest;
try {
request = JSON.parse(payload);
} catch (error) {
logger.error('Error parsing json message: %q', error);
throw error;
}
if(request.ai) {
let matchId = nk.matchCreate(
moduleName, {fast: request.fast, ai: true});
let res: RpcFindMatchResponse = { matchIds: [matchId] };
return JSON.stringify(res);
}
let matches: nkruntime.Match[];
try {
const query = `+label.open:1 +label.fast:${request.fast ? 1 : 0}`;
matches = nk.matchList(10, true, null, null, 1, query);
} catch (error) {
logger.error('Error listing matches: %v', error);
throw error;
}
let matchIds: string[] = [];
if (matches.length > 0) {
// There are one or more ongoing matches the user could join.
matchIds = matches.map(m => m.matchId);
} else {
// No available matches found, create a new one.
try {
matchIds.push(nk.matchCreate(moduleName, {fast: request.fast}));
} catch (error) {
logger.error('Error creating match: %v', error);
throw error;
}
}
let res: RpcFindMatchResponse = { matchIds };
return JSON.stringify(res);
}