TinyBase logoTinyBase β

canSetValue

The canSetValue method lets you allow or disallow any changes to a Value stored on the server, as sent from a client.

canSetValue(
  valueId: string,
  value: Value,
  initialSave: boolean,
  requestOrConnection: Request | Connection,
  oldValue: ValueOrUndefined,
): Promise<boolean>
TypeDescription
valueIdstring
valueValue
initialSaveboolean
requestOrConnectionRequest | Connection
oldValueValueOrUndefined
returnsPromise<boolean>

This is one of the functions use to sanitize the data that is being sent from a client. Perhaps you might want to make sure the server-stored data adheres to a particular schema, or you might want to make certain data read-only. Remember that you cannot trust the client to only send data that the server considers valid or safe.

This method is passed the Value Id that the client is trying to change - as well as the Value itself. The initialSave parameter distinguishes between the first bulk save of the Store to the PartyKit room over HTTP (true), and subsequent incremental updates over a web sockets (false).

The requestOrConnection parameter will either be the HTTP(S) request or the web socket connection, in those two cases respectively. You can, for instance, use this to distinguish between different users.

Since v4.3.13, the final parameter is the Value previously stored on the server, if any. Use this to distinguish between the addition of a new Value (in which case it will be undefined) and the updating of an existing one.

Return false from this method to disallow changes to this Value on the server, or true to allow them. The default implementation returns true to allow all changes.

Example

The following implementation will strip out any attempts by the client to update the 'userId' Value after the initial save:

import {TinyBasePartyKitServer} from 'tinybase/persisters/persister-partykit-server';

export class MyServer extends TinyBasePartyKitServer {
  canSetValue(valueId, value, initialSave) {
    return initialSave || valueId != 'userId';
  }
}

Since

v4.3.12