getPersister
The getPersister method is used to get the Persister that the Durable Object is using, and from that, the MergeableStore that its clients synchronize with.
getPersister(): Persister<MergeableStoreOnly> | undefined| returns | Persister<MergeableStoreOnly> | undefined | The |
|---|
This is useful for when the Durable Object needs to read or change the data itself: in a method that a Worker calls, or when an alarm goes off, for example. Any change made to the MergeableStore is sent to the clients, and is saved, just as if it had come from one of them. It is not checked by the canWriteCell method and canWriteValue method, which only decide what clients may write.
This is the Persister that the createPersister method returned. There is no need to keep hold of it yourself, which is hard to do: that method is called while the Durable Object is being constructed, before any fields of your own class have been initialized. If that method is not overridden, but clients are authorized, this is a Persister that saves nothing, for the in-memory MergeableStore that the Durable Object then uses. Otherwise, this is undefined.
The Persister has finished loading by the time that the Durable Object handles any request, call, alarm, or message. But it is still undefined in the constructor of your own class. To use it as the Durable Object starts, do so in a function passed to the blockConcurrencyWhile method of the DurableObjectState context, once you have called the super constructor.
The Durable Object starts loading and saving automatically, and so there is no need to do that with this Persister. But you can wait for its save method before responding to a call, for example, or destroy it before deleting everything that the Durable Object has stored.
Example
This example adds a method to a Durable Object that a Worker can call to close a shop. Every client sees that it has closed.
import {createMergeableStore} from 'tinybase';
import {createDurableObjectSqlStoragePersister} from 'tinybase/persisters/persister-durable-object-sql-storage';
import {WsServerDurableObject} from 'tinybase/synchronizers/synchronizer-ws-server-durable-object';
export class MyDurableObject extends WsServerDurableObject {
createPersister() {
return createDurableObjectSqlStoragePersister(
createMergeableStore(),
this.ctx.storage.sql,
);
}
closeShop() {
this.getPersister().getStore().setValue('open', false);
}
}
Since
v10.2.0