Coder Social home page Coder Social logo

heroiclabs / nakama-js Goto Github PK

View Code? Open in Web Editor NEW
182.0 182.0 54.0 8.36 MB

JavaScript client for Nakama server written in TypeScript.

Home Page: https://heroiclabs.com/docs/nakama/client-libraries/javascript/

License: Apache License 2.0

HTML 0.31% JavaScript 0.94% TypeScript 96.54% CSS 0.08% Starlark 0.05% Java 0.51% Objective-C 0.36% Ruby 0.07% Go 1.13%
game-server javascript-client nakama nakama-js nakama-server react-native realtime realtime-chat

nakama-js's People

Contributors

ale-sg avatar attackgoat avatar blaizer avatar danial23 avatar dependabot[bot] avatar dimon4eg avatar docsncode avatar dp0ch avatar dragonlobster avatar f4th4n avatar fabifink avatar flaviofernandes004 avatar foundrium avatar gmertk avatar gpene avatar jackunion avatar lugehorsam avatar maciejmrozinski avatar miltoncandelero avatar mofirouz avatar nikitaosyak avatar novabyte avatar obmsg avatar ricky26 avatar robinmaree avatar sesposito avatar tomglenn avatar vonagam avatar zengjie avatar zyro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nakama-js's Issues

Module support

nakama-js seems to stop working once a project uses ES6 modules. For example, simply doing this:

import { Client } from "@heroiclabs/nakama-js"
const client = new Client()

Results in error:

import { Client } from "@heroiclabs/nakama-js";
         ^^^^^^
SyntaxError: Named export 'Client' not found. The requested module '@heroiclabs/nakama-js' is a CommonJS module, which may not support all module.exports as named exports.

It instead suggests importing it like:

import nakama from "@heroiclabs/nakama-js"
const {Client} = nakama

But that instead throws another error:

   import nakama from "@heroiclabs/nakama-js"
          ^
   const { Client } = nakama
> 'default' is not exported by node_modules/@heroiclabs/nakama-js/dist/nakama-js.esm.js

Seems to be related to using TypeScript with "module": "es2020".

issues with generatecid

I'm trying to use nakama-js client in cocos2d-x project with java script.
Don't want not use outdated nakama C++ client and write bindings to use it in my js project.

original generatecid:

DefaultSocket.prototype.generatecid = function () {
    return __spread(Array(30)).map(function () { return Math.random().toString(36)[3]; }).join('');
};
  1. First issue with generatecid on native platforms where cocos uses spidermonkey as js engine.
    The generatecid returns empty string and as result sockets doesn't work properly.
    It seems Array.map doesn't iterate when elements are nulls.

  2. Second issue - as Math.random() might return 0 in this case generatecid will return cid with "undefined" word inside. e.g. 20undefineddra7tl3k9iuzzwl78m2m87rduph
    Maybe this is not a problem. Just wanted to inform you.

I fixed the issues in following manner:

DefaultSocket.prototype.generatecid = function () {
    var cid = "";
    for (var i=0; i < 30; ++i) {
        var s = Math.random().toString(36);

        if (s.length > 2)
            cid = cid.concat(s[3]);
        else
            cid = cid.concat(s[0]);
    }
    return cid;
};

P.S. My simple implementation works faster than original one by 15%. Tested on latest Chrome.

Javascript - Socket RPC never resolved or rejected when disconnected

Hi, when making an RPC call while the network is turned off it never resolves or rejects.
I assume this is not the intended behavior right?

As you an see in this gif the first request works properly when connected.
Then I turn off the wifi and send another request, it's called but never resolved or rejected.
Even when I turn my wifi back on.

ws_rpc_hangs

Generate missing Facebook Instant Games authentications functionality

Facebook Instant Games authentication was added to the server but not to the JS SDK (which would be how most games would end up using it).

Can you generate the API functionality defined in https://github.com/heroiclabs/nakama/blob/master/apigrpc/apigrpc.proto#L166

this will allow for:

const useSSL = false; // Enable if server is run with an SSL certificate.
const client = new nakamajs.Client("defaultkey", "127.0.0.1", 7350, useSSL);
const signedPlayerInfo = await FBInstant.player. getSignedPlayerInfoAsync();
const session = await client.authenticateFacebookInstantGame({
  account: {
    signedPlayerInfo: signedPlayerInfo,
    vars: {}
  }
 create: true
});
console.info(session);

401 Unauthorized Error while renewing session

While re-authentication of a device, server always returns 401.

I believe this is because of an old bearerToken which is not cleared during the server authentication request.

I will try to open a pull request. : failed, because I couldn't manage to run the tests. I will not open a pull request.

to reproduce:
Create a short session using client.authenticateDevice(id);
wait until it expires.
try to create another session using client.authenticateDevice(id);

Error message:
{"type":"default","status":401,"ok":false,"statusText":"","headers":{"map":{"content-encoding":"gzip","cache-control":"no-store, no-cache, must-revalidate","content-length":"66","content-type":"application/json","vary":"Accept-Encoding","date":"Mon, 24 May 2021 22:40:02 GMT"}},"url":"http://127.0.0.1:7350/v2/account/authenticate/device?","bodyUsed":false,"_bodyInit":{"_data":{"size":42,"offset":0,"blobId":"95393CD0-52C6-41B2-A924-19B810B1FA20","type":"application/json","name":"device","__collector":{}}},"_bodyBlob":{"_data":{"size":42,"offset":0,"blobId":"95393CD0-52C6-41B2-A924-19B810B1FA20","type":"application/json","name":"device","__collector":{}}}}

How to build source

I've trying to build sources on Mac and Linux and can't do this.

Mac OS:
изображение

Linux:
изображение
изображение

How can i fix this?

Error importing nakamajs

There seems to be a bug in the packaging of the JS SDK
Moving from Rollup over to using esbuild might have created the bug

yarn add @heroiclabs/nakama-js
import * as nakamajs from "@heroiclabs/nakama-js";

error: Error: While trying to resolve module `@heroiclabs/nakama-js` from file `C:\Users\simtj\Desktop\NakamaClient\App.js`, the package `C:\Users\simtj\Desktop\NakamaClient\node_modules\@heroiclabs\nakama-js\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`C:\Users\simtj\Desktop\NakamaClient\node_modules\@heroiclabs\nakama-js\packages\nakama-js\dist\nakama-js.iife.js`. Indeed, none of these files exist:

  * C:\Users\simtj\Desktop\NakamaClient\node_modules\@heroiclabs\nakama-js\packages\nakama-js\dist\nakama-js.iife.js(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
  * C:\Users\simtj\Desktop\NakamaClient\node_modules\@heroiclabs\nakama-js\packages\nakama-js\dist\nakama-js.iife.js\index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)

Authenticating Facebook Users Friends Causes Error

When I'm trying to register two users that are friends through FB on Nakama I'm getting a weird error saying, Could not register: { "code": 6, "message": "ID already in use",
Does anyone have any idea how that could be happening?
I'm not seeing any ID's between the two users that are the same.

The weird thing is I've test it many ways, I've cleared my backend database and registered 3 users in different orders.
When I do Un-friended, Un-friended both users register fine
if I do Un-friended, friended, friended it errors out on the 2nd friended user
Doesn't matter what the order of accounts are it always errors out on the 2nd friended user and will work fine for any users that aren't on each other friend's list.

It is going through the normal flow of authenticating a user, it is giving an error code 5 stating that the {"code":5,"message":"ID not found","request": and then giving an error of: Error: { "code": 6, "message": "ID already in use", "request":

It can be separated. If I register John (friends with Nick), Greg (no friends in common, and Nick (friends with John) it will work until I register with Nick

authenticateEmail with username fails

The docs on email authentication explain that you can specify a username when creating a new account when calling authenticateEmail, e.g. const session = await client.authenticateEmail(email, password, create, "mycustomusername");

Full snippet that reproduces the issue with a local docker setup of Nakama using the Docker Compose file here with default settings:

const client = new nakamajs.Client('defaultkey', '127.0.0.1', '7350', false);
const socket = client.createSocket(false, false);
client.authenticateEmail('[email protected]', 'Password1', true, 'mycustomusername');

I can see the resulting request from this snippet in the Chrome dev tools network tab to http://127.0.0.1:7350/v2/account/authenticate/email? (no url params) with the body

{"email":"[email protected]","password":"Password1","vars":true}

This request fails with status code 400 and no body. The curl example in the docs indicates the username needs to be sent as a URL parameter, but the javascript library doesn't appear to add it as a url parameter.

Using versions:

  • Javascript library: 2.1.3 (iife)
  • Nakama server: Docker Compose setup on local machine, version 2.12.0+650b506a deployed with no changes from the compose file here

[Feature Request] Support Sign In With Apple

The Nakama Server has Sign In With Apple support

For those of us building games with Expo, React Native and other mobile JS approaches, we must provide a way for people to sign in with Apple, otherwise our apps will be rejected by Apple.

Add safety checks to postMessage usage

This issue may have already been fixed, but opening it here because it was reported with us ~2 years ago.

Currently nakama uses iframes with postMessage to relay messages internally. Other scripts can also use the postMessage API, and currently nakama.js seems to be able to crash when another script posts a message that it doesn't recognize.

Nakama.js should do checks for the properties it expects on incoming messages.

Related to MetaMask/metamask-extension#5533

jsBase64 undefined with v2.1.4

Upon updating to v2.1.4 we were getting an error when trying to authenticate with Email. Installed by downloading the file from release and importing it as specified through the docs. We were able to authorize with 2.1.3. Calling jsBase64 from console returns undefined.

Error:

An error occured while authorizing: TypeError: Cannot read property 'encode' of undefined
    at NakamaApi.doFetch (nakama-js.umd.js:567)
    at NakamaApi.authenticateEmail (nakama-js.umd.js:677)
    at Client.authenticateEmail (nakama-js.umd.js:2062)
    at registerUser (nakama-interface.js:7)
    at Array.<anonymous> (main.js:18)
    at Function.f (elm.compiled.js:2219)
    at A3 (elm.compiled.js:59)
    at Object.b (elm.compiled.js:1978)
    at _Scheduler_step (elm.compiled.js:1822)
    at _Scheduler_enqueue (elm.compiled.js:1784)

Local Scope with breakpoint at line nakama-js.umd.js:567:

Local
    body: "{"email":"[email protected]","password":"password1234"}"
    descriptor:
        configurable: true
        enumerable: true
        get: ƒ withCredentials()
        set: ƒ withCredentials()
        __proto__: Object
    fetchOptions: {method: "POST", headers: {…}}
    method: "POST"
    options:
        __proto__: Object
    queryParams:
        create: false
        username: "none"
        __proto__: Object
    this: NakamaApi
        configuration:
            basePath: "http://127.0.0.1:7350"
            password: ""
            timeoutMs: 7000
            username: "defaultKey"
            __proto__: Object
        __proto__: Object
    urlPath: "/v2/account/authenticate/email"
    urlQuery: "?create=false&username=none&"
    _this: NakamaApi
        configuration:
            basePath: "http://127.0.0.1:7350"
            password: ""
            timeoutMs: 7000
            username: "defaultKey"
            __proto__: Object
        __proto__: Object

nakama-js client error in Cocos Creator building for the Facebook Instant Games platform

Using nakama-js.umd.js (v0.4.0) as a plugin script in Cocos Creator 1.9.1 causes a fail at building for Facebook Instant Platform.

Steps to replicate:

  1. Create new project on Cocos Creator

captura de pantalla 2018-04-28 a la s 14 27 30

2. Drag and drop the "nakama-js.umd.js" file into the projects assets

captura de pantalla 2018-04-28 a la s 14 20 30

3. On properties panel of the "nakama-js.umd.js" file select "Import as Plugin"

captura de pantalla 2018-04-28 a la s 14 20 34

4. Go to "Project" -> "Build..."

captura de pantalla 2018-04-28 a la s 14 28 08

5. Select "Facebook Instant Games" as platform. 6. Build:

captura de pantalla 2018-04-28 a la s 14 22 41


With the esm version the build works but it gives this error running the project in development on Chrome:
captura de pantalla 2018-04-28 a la s 15 07 40


With the cjs version gives the same error that umd version and it gives this error running the project in development on Chrome:
captura de pantalla 2018-04-28 a la s 15 11 32

How to enable nodejs support

  • Take cjs release
  • Install following packages: es6-promise, isomorphic-fetch, url-search-params, ws
  • Monkey patch the cjs release (on top of the file):
// nakama-js.cjs.js
require('es6-promise').polyfill();
require('isomorphic-fetch');
const URLSearchParams = require('url-search-params')
var WebSocket = require('ws')
var self = {} // dont forget this also, in node this object will not be created
  • Use it like in examples, just don't forget to require it
// app.js
const nakamajs = require('/.nakama-js.cjs')
const client = new nakamajs.Client('defaultkey', '127.0.0.1')

[ReferenceError: Can't find variable: btoa]

React-native [ReferenceError: Can't find variable: btoa]

Hi there,
I'm using @heroiclabs/nakama-js(^2.1.3") in react-native(^0.63.2). And this is the first time I'm using nakama in react native.

My issue is while I'm calling,

 client.authenticateCustom(sessionToken, create, user_id );

I'm getting error,
[ReferenceError: Can't find variable: btoa]
Screenshot 2021-01-17 025442

=====================================================================================

If I tooked build for android then it crashed my application, I'm getting like this -->
Screenshot 2021-01-17 025247

=====================================================================================

But if I debugged through browser then it get success.
WhatsApp Image 2021-01-17 at 3 00 12 AM

I tried it in react-js then it works perfectly.

=====================================================================================

Now I need a solution for this [ReferenceError: Can't find variable: btoa] . Please fix it ASAP.

Assuming window and fetch

The client assumes it is running in a browser but since it is an npm registered package it should also run in node.

This can easily be archived by replacing window.console with

typeof console !== 'undefined'

And usage of node-fetch if fetch is not available already

Javascript - Sent messages with verbose logger are logged base64 encoded

When verbose logging is turned on all received messages are in plain text but sent messages are logged already encoded.

This could be fixed by putting the data into the message, logging it and then doing the encode. at the moment it logs at the end of the send method of default socket.

net::ERR_CONNECTION_REFUSED

This function is returning error net::ERR_CONNECTION_REFUSED

    nakamatest:function(){
        var client=new nakamajs.Client("defaultkey","127.0.0.1",7350);
        client.ssl=false;
        var sessionHandler=function(session)
        {
            console.log("Session: %o"+session);
            client.connect(session).then(function(session)
            {
                console.log("session connected");
                localStorage.nakamaToken=session.token;
            }).catch(function(error){
                console.log("an error occured during connection "+error);
            });
        }
        //login or register
        var errorHandler=function(error)
        {
            console.log(error);
        };
        var message= nakamajs.AuthenticateRequest.email("[email protected]","truepassword");
        client.login(message).then(sessionHandler).catch(function (error)
        {
                client.register(message).then(sessionHandler).catch(errorHandler);
        });
    },

The docker container started without errors[see image]
https://ibb.co/cA4187

Nakama-js is no longer available on npm

I'm not sure if this is the right forum for this issue.

Currently nakama-js is not published on NPM which makes it a little difficult to manage, and may cause newcomers issues getting started with Nakama.

No way to efficiently send binary data (Base64 may be unnecessary)

Currently the data field of a MatchDataSend message is processed bybtoa(JSON.stringify(data)) (and the inverse is done for receiving match data). If I want to send data efficiently, I'd like that data field to be as few bytes as possible. The problem is that both JSON.stringify and btoa are increasing the size of the message, for example:

image

As you can see, when I'm sending string data JSON.stringify adds an extra pair of "" onto the string, and adds some extra escape characters for non-printable characters. Then btoa increases the size of the string by another ~25%. But, before btoa comes along, the data is already "cleaned" of any non-printable characters by the JSON.stringify.

So that's why I'm unsure why btoa is even necessary, it seems to be only adding extra overhead. Furthermore, it actually breaks if you try to send non-ASCII/Latin1 data:

image

So I think at the very least atob/btoa should be considered for removal (although this would be a backcompat-breaking change) and we should think about some way of sending binary data efficiently (although I'm not much of a JavaScript guru so I don't' have the answers here).

Incorporate test dependencies on Lua runtime code in data/modules

Several tests fail on a fresh install due to the client code assuming certain test RPC functions have been loaded into the local Nakama instance.

For example, the following test fails:
should create leaderboard with Set operator and then list leaderboard records

because the Lua method clientrpc.create_leaderboard is not mounted to my container's nakama/data_modules folder.

Obviously we want the ability to test custom RPC functions from any client library, and this necessitates some test data from nakama/data_modules.

So there are a couple different approaches I can think of to solve this, in order from least to most involved:

(1) Simply document that the test RPC data in Nakama must be mounted to the local instance.

(2) Include a docker-compose and copy of the test data to mount inside this repo.

(3) Publish a test image with these functions baked in, and run that image as part of the integration tests for any client library.

That last one feels like the best long term solution, but happy to do whatever.

Realtime parties

Does the javascript sdk support the nakama's 3.0 feature realtime parties ?

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

Hi there,
I'm using heroiclabs/nakama-js v. 2.1.5.

I've included in my web page this js:
<script src="nakama-js.iife.js"></script>

Following the documentation I had no problems creating the client, but I have problems creating the session. More precisely on the console I get the following error:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

My code is the following:

var client = new nakamajs.Client("defaultkey", "myserverIP", "7350", true);
const customId = "45678";
const session = await client.authenticateCustom(customId)
localStorage.nakamaAuthToken = session.token;

const useSSL = true;
const verboseLogging = true;
// Send presence events to subscribed users.
const createStatus = false;
const socket = client.createSocket(useSSL, verboseLogging);
session = await socket.connect(session, createStatus)

const channelId = "Room1";
const persistence = true;
const hidden = true;

var response = await socket.joinChat(channelId, 1, persistence, hidden);
console.info("Successfully joined channel:", response.channel.id);

TypeError: nakamajs.UsersFetchMessage is not a constructor

According to the docs at https://heroiclabs.com/docs/user-accounts/ I try to fetch users by ID.

But it seems there is no such function UsersFetchMessage, because the console error I get is:
An error occured during session connection: TypeError: nakamajs.UsersFetchMessage is not a constructor

Websocket disconnect event not fired immediately

When disconnecting the WIFI the Websocket disconnect event is not fired.
It seems like that it's only fired after like 30 seconds or when enabling the wifi again.
socket.ondisconnect = this._onDisconnected.bind(this);

As you can see in the gif here I added a breakpoint but it's never triggered.
Only when I turn the wifi back on it's triggered.
ws_disconnect

Run test with newest server: 2 failed

  1. test\socket-match.test.js
    ● Match Tests › should create match

    expect(received)[.not].toHaveLength(length)

    Expected value to have a 'length' property that is a number. Received:
    undefined

    56 | expect(response.match).not.toBeNull();
    57 | expect(response.match.match_id).not.toBeNull();

    58 | expect(response.match.presences).toHaveLength(1);
    59 | expect(response.match.self).not.toBeNull();
    60 | expect(response.match.self.session_id).not.toBeNull();
    61 | expect(response.match.self.user_id).not.toBeNull();

    at Object.it (test/socket-match.test.js:58:38)

  2. test\client-authenticate.test.js
    ● Console
    console.log test\client-authenticate.test.js:33
    PAGE LOG ERROR: Error: Response
    at Page._handleException (D:\nakama-js-master\node_modules\puppeteer\lib\Page.js:409:38)
    at CDPSession.Page.client.on.exception (D:\nakama-js-master\node_modules\puppeteer\lib\Page.js:102:60)
    at emitOne (events.js:116:13)
    at CDPSession.emit (events.js:211:7)
    at CDPSession._onMessage (D:\nakama-js-master\node_modules\puppeteer\lib\Connection.js:215:12)
    at Connection._onMessage (D:\nakama-js-master\node_modules\puppeteer\lib\Connection.js:117:19)
    at emitOne (events.js:116:13)
    at WebSocket.emit (events.js:211:7)
    at Receiver._receiver.onmessage (D:\nakama-js-master\node_modules\ws\lib\WebSocket.js:141:47)
    at Receiver.dataMessage (D:\nakama-js-master\node_modules\ws\lib\Receiver.js:389:14)
    ● Authenticate Tests › should fail to authenticate with new custom id
    Evaluation failed: Response
    at ExecutionContext.evaluateHandle (node_modules/puppeteer/lib/ExecutionContext.js:75:13)

btoa is undefined (atob is undefined)

Problem:

Hi, if you have this problem you are going to take nakama-umd.js from here and replace base64 encryption (especially btoa, atoa methods) with your custom ones.

Solution:

Here is the solution, it is rewritten nakama javascript library with replaced encryption methods (for v2.0.1).
For example:
nakama-js.umd.js.zip

Variables not passed on authentication

When passing variables with authentication they don't get sent to the server.
This is due to the variables being added as a map in the body and the body then gets parsed to JSON.
But since it's a map this doesn't work so the client will always send an empty object for the variables.

Here you can see it if you add a breakpoint.
image

Wanted to make a MR but saw it was generated code so not sure what changes to make exactly but it would be great if this can be fixed because we want to restrict users with older clients from being able to authenticate.

Javascript - Change .d.ts file to respect nullability?

Hey folks, I was going through some of the d.ts files and spotted that the types don't necessarily match the nullability in the db, for example:

export interface Group {
    avatar_url?: string;
    create_time?: string;
    creator_id?: string;
    description?: string;
    edge_count?: number;
    id?: string;
    lang_tag?: string;
    max_count?: number;
    metadata?: {};
    name?: string;
    open?: boolean;
    update_time?: string;
}

vs

Screen Shot 2021-12-26 at 3 55 05 PM

Which implies at least id, creator_id, name, metadata should be not marked as nullable. Is there something I am missing (e.g. partial requests etc)? If not, I can figure a way to update the .d.ts files to take this into account.

Cannot find module @heroiclabs/nakama-js with NPM

Installing nakama-js with NPM results in a directory just containing the README, the package.json and the .gitignore.

The nakama-js module has a .gitignore with the dist/ directory in and I think since there's no .npmignore it falls back to using that to filter which files get installed.

[Feature Request] Tutorial of Nakama-JS integration with Boardgame.io

As of now I think the introductory docs are a little sparse, especially for newer developers. I think it'd be great a way for the community to see first hand how Nakama would be implemented with another framework. I think BoardGame would be a good fit since its UI agnostic (among other things)

I'm actually trying to doing this myself but I just wanted to open up a dialogue here in case anyone had any advice or suggestions for getting started.

client.linkEmail returns error code 400 - Bad Request

If I call
await client.linkEmail(session, email, password);
It raises an error code 400 - Bad Request.
The email is not already in use in another account.
authenticateEmail with create=true works.
Calling LinkEmailAsync with Unity client on the same server works.

Match listings in javascript SDK

I am trying to use the Match listings function in my javascript client, but it always returns an empty result without any errors or exceptions.
Following the code that I used:

let matches=this.client.listMatches(this.session);

Is there anything I am missing?

connect method raises "Can't find variable: URLSearchParams" in React Native

Hi folks,
I'm trying to use this lib in a React Native project. Calling connect:

    this.client
      .connect(session)
      .then(function(session) {
        console.log("Session connected.");

        // This returns a promise - if it fails, we are catching the error in the `error` callback below
        return AsyncStorage.setItem("@MyApp:nakamajsToken", session.token);
      })

raises "An error occured: %o [ReferenceError: Can't find variable: URLSearchParams]" due to https://github.com/heroiclabs/nakama-js/blob/master/src/Client.js#L61

window is undefined

Any chance to add check for typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {}
instead of typeof self !== 'undefined' ? self : window
in line 468 - nakama-js.umd.js.

I use server rendering and compiler is giving me trouble since code references “browser globals” like window...

Errors not decoded (unreadable)

I'm trying to read errors sent by our backend (Golang) in the client but I'm unable to do so.
The error.body is a ReadableStream which contains an Uint8Array.
I have no clue how to decode these error messages and it's quite annoying not being able to see errors on the client.
I asked on Gitter and was told to make an issue because this SDK should handle the decoding of errors.

I also noticed error.type is cors, not sure why that is?

Backend: github.com/heroiclabs/nakama-common v1.18.0
Frontend: "@heroiclabs/nakama-js": "^2.3.0"

This is the error object:
image

Here is the code in case I'm just doing something wrong

backendSDK.sendRPC("ADD_BOT_MESSAGE", xxx).catch((err) =>
		{
			console.error(err);
			if (err.body)
			{
				const reader: ReadableStreamDefaultReader<unknown> = (err.body as ReadableStream).getReader();
				reader.read().then((res) =>
				{
					console.error(res);
				}).catch((error: unknown) =>
				{
					console.error(error);
				});
			}
		});
	public async sendRPC(id: string, msg: Uint8Array): Promise<Uint8Array>
	{
		const session: Session = await this.waitForConnection();
		return this._client.rpc(session, id, Networking.encode(msg)).then((response) =>
		{
			return Networking.decode(response.payload);
		});
	}

And on the backend I just return an error in RPC function

func AddBotMessageRPC(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, payload string) (string, error) {
	userID, ok := ctx.Value(runtime.RUNTIME_CTX_USER_ID).(string)
	if !ok {
		return "", errors.New("invalid context, missing userID")
	}
	...
}

Created chat room doesn't return a Topic ID

According to the documentation at https://heroiclabs.com/docs/social-realtime-chat/#send-messages I try to send a message to the created room:

// Join a chat room
var roomId;
var roomName = "Room-Name";

var message = new nakamajs.TopicsJoinRequest();
message.room(roomName);
client.send(message).then(function(result) {
  roomId = result.topics[0].topic;
  console.log("Successfully joined the room: %o", roomId);
}).catch(function(error){
  console.log("An error occured: %o", error);
});


// Send message
var chatTopicId = roomId; // A chat topic ID
var data = {"some":"data"};

var message = new nakamajs.TopicMessageSendRequest();
message.topic = chatTopicId;
message.data = data;
client.send(message).then(function(ack) {
  console.log("New message sent has id %@.", ack.messageId);
}).catch(function(error){
  console.log("An error occured: %o", error);
})

Console logs show that room was joined successfully, but topic ID is missing:

Successfully joined the room: {room: "Room-Name"}
An error occured: {code: 3, message: "Topic ID is required"}

As I understand - instead of Topic ID I have a JSON with room name only. Am I missing something?

Typo in UnlinkRequest

function build_ () should return { unlink: { custom } } instead of return { link: { custom } }

Refer to Gist

Typo in client.js

There is a typo in client.js in the line :
p.resolve({id: message.rcp.id, payload: message.rpc.payload});

The correct one should be:

p.resolve({id: message.rpc.id, payload: message.rpc.payload});

Convert in-line comments to TS official comments

For the TypeDoc generator to pick up field comments and docs, they need to follow the JS/TS official docs format.

So from this:

/** A list of tournaments. */
export interface TournamentList {
  // The list of tournaments returned.
  tournaments?: Array<Tournament>;
  // A pagination cursor (optional).
  cursor?: string,
}

to

/** A list of tournaments. */
export interface TournamentList {
  /** The list of tournaments returned. */
  tournaments?: Array<Tournament>;
  /** A pagination cursor (optional). */
  cursor?: string,
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.