|
| 1 | +## SpacetimeDB SDK |
| 2 | + |
| 3 | +### Overview |
| 4 | + |
| 5 | +This repository contains the TypeScript SDK for SpacetimeDB. The SDK allows to interact with the database server and is prepared to work with code generated from a SpacetimeDB backend code. |
| 6 | + |
| 7 | +### Installation |
| 8 | + |
| 9 | +The SDK is an NPM package, thus you can use your package manager of choice like NPM or Yarn, for example: |
| 10 | + |
| 11 | +``` |
| 12 | +npm install --save @clockworklabs/spacetimedb-typescript-sdk |
| 13 | +``` |
| 14 | + |
| 15 | +You can use the package in the browser, using a bundler like webpack of vite, and in terminal applications |
| 16 | + |
| 17 | +### Usage |
| 18 | + |
| 19 | +In order to connect to a database you have to create a new client: |
| 20 | + |
| 21 | +```ts |
| 22 | +import { SpacetimeDBClient } from '@clockworklabs/spacetimedb-typescript-sdk'; |
| 23 | + |
| 24 | +let client = new SpacetimeDBClient("spacetimedb.com/spacetimedb", "<db-name>"); |
| 25 | +``` |
| 26 | + |
| 27 | +This will connect to a database instance without a specified identity. If you want to persist an identity fetched on connection you can register an `onConnect` callback, which will receive a new assigned identity as an argument: |
| 28 | + |
| 29 | +```ts |
| 30 | +client.onConnect((identity: string) => { |
| 31 | + console.log(identity); |
| 32 | + console.log(client.token); |
| 33 | +}); |
| 34 | +``` |
| 35 | + |
| 36 | +You may also pass credentials as an optional third argument: |
| 37 | + |
| 38 | +```ts |
| 39 | +let credentials = { identity: "<identity>", token: "<token>" }; |
| 40 | +let client = new SpacetimeDBClient("spacetimedb.com/spacetimedb", "<db-name>", credentials); |
| 41 | +``` |
| 42 | + |
| 43 | +Typically, you will use the SDK with types generated from a backend DB service. For example, given a component named `Player` you can subscribe to player updates by registering the component: |
| 44 | + |
| 45 | +```ts |
| 46 | +client.registerComponent(Player, "Player"); |
| 47 | +``` |
| 48 | + |
| 49 | +Then you will be able to register callbacks on insert and delete events, for example: |
| 50 | + |
| 51 | +```ts |
| 52 | +Player.onInsert((newPlayer: Player) => { |
| 53 | + console.log(newPlayer); |
| 54 | +}); |
| 55 | +``` |
| 56 | + |
| 57 | +Given a reducer called `CreatePlayer` you can call it using a call method: |
| 58 | + |
| 59 | +```ts |
| 60 | +CreatePlayer.call("Nickname"); |
| 61 | +``` |
| 62 | + |
0 commit comments