mezon-js 2.7.1

Sign up to get free protection for your applications and to get access to all the features.
package/README.md ADDED
@@ -0,0 +1,244 @@
1
+ Mezon JavaScript client
2
+ ========================
3
+
4
+ > JavaScript client for Mezon server written in TypeScript. For browser and React Native projects.
5
+
6
+ [Mezon](https://github.com/heroiclabs/mezon) is an open-source server designed to power modern games and apps. Features include user accounts, chat, social, matchmaker, realtime multiplayer, and much [more](https://heroiclabs.com).
7
+
8
+ This client implements the full API and socket options with the server. It's written in TypeScript with minimal dependencies to be compatible with all modern browsers and React Native.
9
+
10
+ Full documentation is online - https://heroiclabs.com/docs/javascript-client-guide
11
+
12
+ ## Getting Started
13
+
14
+ You'll need to setup the server and database before you can connect with the client. The simplest way is to use Docker but have a look at the [server documentation](https://github.com/heroiclabs/mezon#getting-started) for other options.
15
+
16
+ 1. Install and run the servers. Follow these [instructions](https://heroiclabs.com/docs/install-docker-quickstart).
17
+
18
+ 2. Import the client into your project. It's [available on NPM](https://www.npmjs.com/package/@mezon/mezon-js) and can be also be added to a project with Bower or other package managers.
19
+
20
+ ```shell
21
+ npm install @mezon/mezon-js
22
+ ```
23
+
24
+ You'll now see the code in the "node_modules" folder and package listed in your "package.json".
25
+
26
+ Optionally, if you would like to use the Protocol Buffers wire format with your sockets, you can import the adapter found in this package:
27
+
28
+ ```shell
29
+ npm install @mezon/mezon-js-protobuf
30
+ ```
31
+
32
+ 3. Use the connection credentials to build a client object.
33
+
34
+ ```js
35
+ import {Client} from "@mezon/mezon-js";
36
+
37
+ var useSSL = false; // Enable if server is run with an SSL certificate.
38
+ var client = new Client("defaultkey", "127.0.0.1", "7350", useSSL);
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ The client object has many methods to execute various features in the server or open realtime socket connections with the server.
44
+
45
+ ### Authenticate
46
+
47
+ There's a variety of ways to [authenticate](https://heroiclabs.com/docs/authentication) with the server. Authentication can create a user if they don't already exist with those credentials. It's also easy to authenticate with a social profile from Google Play Games, Facebook, Game Center, etc.
48
+
49
+ ```js
50
+ var email = "super@heroes.com";
51
+ var password = "batsignal";
52
+ const session = await client.authenticateEmail(email, password);
53
+ console.info(session);
54
+ ```
55
+
56
+ ### Sessions
57
+
58
+ When authenticated the server responds with an auth token (JWT) which contains useful properties and gets deserialized into a `Session` object.
59
+
60
+ ```js
61
+ console.info(session.token); // raw JWT token
62
+ console.info(session.refreshToken); // refresh token
63
+ console.info(session.userId);
64
+ console.info(session.username);
65
+ console.info("Session has expired?", session.isexpired(Date.now() / 1000));
66
+ const expiresat = session.expires_at;
67
+ console.warn("Session will expire at", new Date(expiresat * 1000).toISOString());
68
+ ```
69
+
70
+ It is recommended to store the auth token from the session and check at startup if it has expired. If the token has expired you must reauthenticate. The expiry time of the token can be changed as a setting in the server.
71
+
72
+ ```js
73
+ // Assume we've stored the auth token in browser Web Storage.
74
+ const authtoken = window.localStorage.getItem("nkauthtoken");
75
+ const refreshtoken = window.localStorage.getItem("nkrefreshtoken");
76
+
77
+ let session = mezonjs.Session.restore(authtoken, refreshtoken);
78
+
79
+ // Check whether a session is close to expiry.
80
+
81
+ const unixTimeInFuture = Date.now() + 8.64e+7; // one day from now
82
+
83
+ if (session.isexpired(unixTimeInFuture / 1000)) {
84
+ try
85
+ {
86
+ session = await client.sessionRefresh(session);
87
+ }
88
+ catch (e)
89
+ {
90
+ console.info("Session can no longer be refreshed. Must reauthenticate!");
91
+ }
92
+ }
93
+ ```
94
+
95
+ ### Requests
96
+
97
+ The client includes lots of builtin APIs for various features of the game server. These can be accessed with the methods which return Promise objects. It can also call custom logic as RPC functions on the server. These can also be executed with a socket object.
98
+
99
+ All requests are sent with a session object which authorizes the client.
100
+
101
+ ```js
102
+ const account = await client.getAccount(session);
103
+ console.info(account.user.id);
104
+ console.info(account.user.username);
105
+ console.info(account.wallet);
106
+ ```
107
+
108
+ ### Socket
109
+
110
+ The client can create one or more sockets with the server. Each socket can have it's own event listeners registered for responses received from the server.
111
+
112
+ ```js
113
+ const secure = false; // Enable if server is run with an SSL certificate
114
+ const trace = false;
115
+ const socket = client.createSocket(secure, trace);
116
+ socket.ondisconnect = (evt) => {
117
+ console.info("Disconnected", evt);
118
+ };
119
+
120
+ const session = await socket.connect(session);
121
+ // Socket is open.
122
+ ```
123
+
124
+ If you are using the optional protocol buffer adapter, pass the adapter to the Socket object during construction:
125
+
126
+ ```js
127
+ import {WebSocketAdapterPb} from "@mezon/mezon-js-protobuf"
128
+
129
+ const secure = false; // Enable if server is run with an SSL certificate
130
+ const trace = false;
131
+ const socket = client.createSocket(secure, trace, new WebSocketAdapterPb());
132
+ ```
133
+
134
+ There's many messages for chat, realtime, status events, notifications, etc. which can be sent or received from the socket.
135
+
136
+ ```js
137
+ socket.onchannelmessage = (message) => {
138
+ console.info("Message received from channel", message.channel_id);
139
+ console.info("Received message", message);
140
+ };
141
+
142
+
143
+ // 1 = channel, 2 = Direct Message, 3 = Group
144
+ const type : number = 1;
145
+ const roomname = "mychannel";
146
+ const persistence : boolean = false;
147
+ const hidden : boolean = false;
148
+
149
+ const channel = await socket.joinChat(type, roomname, persistence, hidden);
150
+
151
+ const message = { "hello": "world" };
152
+ socket.writeChatMessage(channel.channel.id, message);
153
+ ```
154
+
155
+ ## Handling errors
156
+
157
+ For any errors in client requests, we return the original error objects from the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
158
+
159
+ In order to capture the Mezon server response associated with the error, when you wrap your client requests in a `try...catch` statement you can invoke `await error.json()` on the `error` object in the catch block:
160
+
161
+ ```js
162
+ try {
163
+ const account = await client.getAccount(session);
164
+ console.info(account.user.id);
165
+ console.info(account.user.username);
166
+ console.info(account.wallet);
167
+ } catch (error) {
168
+ console.info("Inner Mezon error", await error.json());
169
+ }
170
+ ```
171
+
172
+ ## Contribute
173
+
174
+ The development roadmap is managed as GitHub issues and pull requests are welcome. If you're interested in enhancing the code please open an issue to discuss the changes or drop in and discuss it in the [community forum](https://forum.heroiclabs.com).
175
+
176
+ ### Source Builds
177
+
178
+ Ensure you are using Node v18>.
179
+
180
+ The codebase is multi-package monorepo written in TypeScript and can be built with [esbuild](https://github.com/evanw/esbuild). All dependencies are managed with NPM.
181
+
182
+ To build from source, first install all workspace dependencies from the repository root with `npm install`.
183
+
184
+ Then to build a specific workspace, pass the `--workspace` flag to your build command, for example:
185
+
186
+ ```shell
187
+ npm run build --workspace=@mezon/mezon-js
188
+ ```
189
+
190
+ ### Run Tests
191
+
192
+ To run tests you will need to run the server and database. Most tests are written as integration tests which execute against the server. A quick approach we use with our test workflow is to use the Docker compose file described in the [documentation](https://heroiclabs.com/docs/install-docker-quickstart).
193
+
194
+ Tests are run against each workspace bundle; if you have made source code changes, you should `npm run build --workspace=<workspace>` prior to running tests.
195
+
196
+ ```shell
197
+ docker-compose -f ./docker-compose.yml up
198
+ npm run test --workspace=@mezon/mezon-js-test
199
+ ```
200
+
201
+ ### Protocol Buffer Web Socket Adapter
202
+
203
+ To update the generated Typescript required for using the protocol buffer adapter, `cd` into
204
+ `packages/mezon-js-protobuf` and run the following:
205
+
206
+ ```shell
207
+ npx protoc \
208
+ --plugin="./node_modules/.bin/protoc-gen-ts_proto" \
209
+ --proto_path=$GOPATH/src/github.com/heroiclabs/mezon-common \
210
+ --ts_proto_out=. \
211
+ --ts_proto_opt=snakeToCamel=false \
212
+ --ts_proto_opt=esModuleInterop=true \
213
+ $GOPATH/src/github.com/heroiclabs/mezon-common/rtapi/realtime.proto \
214
+ $GOPATH/src/github.com/heroiclabs/mezon-common/api/api.proto
215
+ ```
216
+ ```shell
217
+ npx protoc --plugin="./node_modules/.bin/protoc-gen-ts_proto.cmd" --proto_path=../../../mezon-common --ts_proto_out=./ --ts_proto_opt=snakeToCamel=false --ts_proto_opt=esModuleInterop=true ../../../mezon-common/rtapi/realtime.proto ../../../mezon-common/api/api.proto
218
+ ```
219
+
220
+ ```shell
221
+ npx protoc --plugin="./node_modules/.bin/protoc-gen-ts_proto.cmd" --proto_path=../mezon-common --ts_proto_out=. --ts_proto_opt=snakeToCamel=false --ts_proto_opt=esModuleInterop=true ../mezon-common/rtapi/realtime.proto ../mezon-common/api/api.proto
222
+ ```
223
+
224
+ ### Release Process
225
+
226
+ To release onto NPM if you have access to the "@heroiclabs" organization you can use NPM.
227
+
228
+ ```shell
229
+ npm run build --workspace=<workspace> && npm publish --access=public --workspace=<workspace>
230
+ ```
231
+
232
+ ### Generate Docs
233
+
234
+ API docs are generated with typedoc and deployed to GitHub pages.
235
+
236
+ To run typedoc:
237
+
238
+ ```
239
+ npm install && npm run docs
240
+ ```
241
+
242
+ ### License
243
+
244
+ This project is licensed under the [Apache-2 License](https://github.com/heroiclabs/mezon-js/blob/master/LICENSE).