Nakama JavaScript Client

repository·master·Indexed 42 days ago

https://github.com/heroiclabs/nakama-js

A TypeScript-based JavaScript client for the Nakama server, designed for web browsers and React Native environments. It provides full API coverage, real-time socket capabilities, and an optional Protocol Buffers adapter via @heroiclabs/nakama-js-protobuf for improved WebSocket performance.

Tokens
41.5K
Snippets
152
Records
228
Agent score
50%

What's inside Nakama JS

  1. Dependencies and limitations of openapi-gen

    master

    The generated code is designed to be lean and avoids heavy dependencies like Node's url package.

    Dependencies:

    • Implicit usage of fetch (may require a polyfill in certain environments).
    • base64-js.

    Limitations:

    • The generator has only been verified against the Swagger specification generated by the Nakama server. Behavior may vary with other specifications.
  2. Manage user sessions

    master

    A Session object contains the JWT token, a refreshToken, and user details. It is recommended to store the token and refresh token (e.g., in Web Storage) and check for expiry on startup.

    To restore a session from stored tokens:

    const authtoken = window.localStorage.getItem("nkauthtoken");
    const refreshtoken = window.localStorage.getItem("nkrefreshtoken");
    let session = nakamajs.Session.restore(authtoken, refreshtoken);

    To refresh an expired session:

    if (session.isexpired(unixTimeInFuture / 1000)) {
        try {
            session = await client.sessionRefresh(session);
        } catch (e) {
            console.info("Session can no longer be refreshed. Must reauthenticate!");
        }
    }
    // Assume we've stored the auth token in browser Web Storage.
    const authtoken = window.localStorage.getItem("nkauthtoken");
    const refreshtoken = window.localStorage.getItem("nkrefreshtoken");
    
    let session = nakamajs.Session.restore(authtoken, refreshtoken);
    
    // Check whether a session is close to expiry.
    
    const unixTimeInFuture = Date.now() + 8.64e+7; // one day from now
    
    if (session.isexpired(unixTimeInFuture / 1000)) {
        try
        {
            session = await client.sessionRefresh(session);
        }
        catch (e)
        {
            console.info("Session can no longer be refreshed. Must reauthenticate!");
        }
    }
  3. Manage Satori Sessions

    master

    A Session object is returned upon successful authentication. It contains a JWT token, a refreshToken, and an expires_at timestamp (Unix time).

    Key capabilities:

    • Check expiry: Use session.isexpired(unixTimestamp) to check if a session is no longer valid.
    • Restore session: Use Session.restore(authtoken, refreshtoken) to recreate a session from stored credentials (e.g., from Web Storage).
    • Refresh session: Use client.sessionRefresh(session) to obtain a new session using a refresh token if the current one is near expiry.
    // Restore a session from storage
    const authtoken = window.localStorage.getItem("satori_authtoken");
    const refreshtoken = window.localStorage.getItem("satori_refreshtoken");
    let session = satorijs.Session.restore(authtoken, refreshtoken);
    
    // Check if session is close to expiry and refresh if necessary
    const unixTimeInFuture = Date.now() + 8.64e+7; // one day from now
    if (session.isexpired(unixTimeInFuture / 1000)) {
        try {
            session = await client.sessionRefresh(session);
        } catch (e) {
            console.info("Session can no longer be refreshed. Must reauthenticate!");
        }
    }
  4. Generate Satori API client using openapi-gen

    master

    You can also use the openapi-gen utility to generate a TypeScript API client for Satori. Run the main.go file pointing to the Satori Swagger JSON file and specify "Satori" as the target name, redirecting the output to the satori-js package.

    go run main.go "$GOPATH/src/github.com/heroiclabs/satori/api/satori.swagger.json" "Satori" > ../packages/satori-js/api.gen.ts
  5. Configure the Nakama client with the Protobuf adapter

    master

    To use Protocol Buffers over WebSockets, import WebSocketAdapterPb from @heroiclabs/nakama-js-protobuf and pass an instance of it to client.createSocket(). This replaces the default JSON-based socket with one that supports Protobuf encoding/decoding.

    import {Client} from "@heroiclabs/nakama-js";
    import {WebSocketAdapterPb} from "@heroiclabs/nakama-js-protobuf"
    
    const useSSL = false; // Enable if server is run with an SSL certificate.
    const client = new Client("defaultkey", "127.0.0.1", 7350, useSSL);
    
    const trace = false;
    const socket = client.createSocket(useSSL, trace, new WebSocketAdapterPb());
  6. Generate Nakama API client using openapi-gen

    master

    The openapi-gen utility is a command-line tool used to generate a TypeScript API client from a Nakama server's Swagger specification. This allows for the creation of lean, simple code with minimal dependencies compared to standard tools like swagger-codegen.

    To generate the client, run the main.go file pointing to the Nakama Swagger JSON file and specify "Nakama" as the target name. The output should be redirected to the desired destination file in the nakama-js package.

    go run main.go "$GOPATH/src/github.com/heroiclabs/nakama/apigrpc/apigrpc.swagger.json" "Nakama" > ../packages/nakama-js/api.gen.ts