tinybase 6.1.0-beta.1 → 6.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/@types/common/index.d.ts +4 -4
  2. package/@types/common/with-schemas/index.d.ts +4 -4
  3. package/index.js +15 -3
  4. package/indexes/index.js +15 -3
  5. package/indexes/with-schemas/index.js +15 -3
  6. package/min/index.js +1 -1
  7. package/min/index.js.gz +0 -0
  8. package/min/indexes/index.js +1 -1
  9. package/min/indexes/index.js.gz +0 -0
  10. package/min/indexes/with-schemas/index.js +1 -1
  11. package/min/indexes/with-schemas/index.js.gz +0 -0
  12. package/min/with-schemas/index.js +1 -1
  13. package/min/with-schemas/index.js.gz +0 -0
  14. package/package.json +7 -7
  15. package/readme.md +1 -1
  16. package/with-schemas/index.js +15 -3
  17. package/@types/_internal/queries/index.d.cts +0 -0
  18. package/@types/_internal/queries/with-schemas/index.d.cts +0 -22
  19. package/@types/_internal/store/index.d.cts +0 -3
  20. package/@types/_internal/store/with-schemas/index.d.cts +0 -106
  21. package/@types/_internal/ui-react/index.d.cts +0 -0
  22. package/@types/_internal/ui-react/with-schemas/index.d.cts +0 -1130
  23. package/@types/checkpoints/index.d.cts +0 -1059
  24. package/@types/checkpoints/with-schemas/index.d.cts +0 -1151
  25. package/@types/common/index.d.cts +0 -158
  26. package/@types/common/with-schemas/index.d.cts +0 -158
  27. package/@types/index.d.cts +0 -17
  28. package/@types/indexes/index.d.cts +0 -1064
  29. package/@types/indexes/with-schemas/index.d.cts +0 -1210
  30. package/@types/mergeable-store/index.d.cts +0 -1139
  31. package/@types/mergeable-store/with-schemas/index.d.cts +0 -1628
  32. package/@types/metrics/index.d.cts +0 -917
  33. package/@types/metrics/with-schemas/index.d.cts +0 -1004
  34. package/@types/persisters/index.d.cts +0 -1877
  35. package/@types/persisters/persister-automerge/index.d.cts +0 -165
  36. package/@types/persisters/persister-automerge/with-schemas/index.d.cts +0 -180
  37. package/@types/persisters/persister-browser/index.d.cts +0 -185
  38. package/@types/persisters/persister-browser/with-schemas/index.d.cts +0 -208
  39. package/@types/persisters/persister-cr-sqlite-wasm/index.d.cts +0 -159
  40. package/@types/persisters/persister-cr-sqlite-wasm/with-schemas/index.d.cts +0 -178
  41. package/@types/persisters/persister-durable-object-storage/index.d.cts +0 -122
  42. package/@types/persisters/persister-durable-object-storage/with-schemas/index.d.cts +0 -136
  43. package/@types/persisters/persister-electric-sql/index.d.cts +0 -185
  44. package/@types/persisters/persister-electric-sql/with-schemas/index.d.cts +0 -204
  45. package/@types/persisters/persister-expo-sqlite/index.d.cts +0 -186
  46. package/@types/persisters/persister-expo-sqlite/with-schemas/index.d.cts +0 -205
  47. package/@types/persisters/persister-file/index.d.cts +0 -94
  48. package/@types/persisters/persister-file/with-schemas/index.d.cts +0 -107
  49. package/@types/persisters/persister-indexed-db/index.d.cts +0 -120
  50. package/@types/persisters/persister-indexed-db/with-schemas/index.d.cts +0 -135
  51. package/@types/persisters/persister-libsql/index.d.cts +0 -158
  52. package/@types/persisters/persister-libsql/with-schemas/index.d.cts +0 -177
  53. package/@types/persisters/persister-partykit-client/index.d.cts +0 -195
  54. package/@types/persisters/persister-partykit-client/with-schemas/index.d.cts +0 -210
  55. package/@types/persisters/persister-partykit-server/index.d.cts +0 -650
  56. package/@types/persisters/persister-partykit-server/with-schemas/index.d.cts +0 -695
  57. package/@types/persisters/persister-pglite/index.d.cts +0 -177
  58. package/@types/persisters/persister-pglite/with-schemas/index.d.cts +0 -196
  59. package/@types/persisters/persister-postgres/index.d.cts +0 -166
  60. package/@types/persisters/persister-postgres/with-schemas/index.d.cts +0 -185
  61. package/@types/persisters/persister-powersync/index.d.cts +0 -174
  62. package/@types/persisters/persister-powersync/with-schemas/index.d.cts +0 -193
  63. package/@types/persisters/persister-remote/index.d.cts +0 -117
  64. package/@types/persisters/persister-remote/with-schemas/index.d.cts +0 -133
  65. package/@types/persisters/persister-sqlite-wasm/index.d.cts +0 -175
  66. package/@types/persisters/persister-sqlite-wasm/with-schemas/index.d.cts +0 -195
  67. package/@types/persisters/persister-sqlite3/index.d.cts +0 -176
  68. package/@types/persisters/persister-sqlite3/with-schemas/index.d.cts +0 -195
  69. package/@types/persisters/persister-yjs/index.d.cts +0 -161
  70. package/@types/persisters/persister-yjs/with-schemas/index.d.cts +0 -176
  71. package/@types/persisters/with-schemas/index.d.cts +0 -2054
  72. package/@types/queries/index.d.cts +0 -3695
  73. package/@types/queries/with-schemas/index.d.cts +0 -4016
  74. package/@types/relationships/index.d.cts +0 -1320
  75. package/@types/relationships/with-schemas/index.d.cts +0 -1474
  76. package/@types/store/index.d.cts +0 -7598
  77. package/@types/store/with-schemas/index.d.cts +0 -9278
  78. package/@types/synchronizers/index.d.cts +0 -485
  79. package/@types/synchronizers/synchronizer-broadcast-channel/index.d.cts +0 -121
  80. package/@types/synchronizers/synchronizer-broadcast-channel/with-schemas/index.d.cts +0 -137
  81. package/@types/synchronizers/synchronizer-local/index.d.cts +0 -95
  82. package/@types/synchronizers/synchronizer-local/with-schemas/index.d.cts +0 -114
  83. package/@types/synchronizers/synchronizer-ws-client/index.d.cts +0 -160
  84. package/@types/synchronizers/synchronizer-ws-client/with-schemas/index.d.cts +0 -179
  85. package/@types/synchronizers/synchronizer-ws-server/index.d.cts +0 -736
  86. package/@types/synchronizers/synchronizer-ws-server/with-schemas/index.d.cts +0 -765
  87. package/@types/synchronizers/synchronizer-ws-server-durable-object/index.d.cts +0 -311
  88. package/@types/synchronizers/synchronizer-ws-server-durable-object/with-schemas/index.d.cts +0 -349
  89. package/@types/synchronizers/synchronizer-ws-server-simple/index.d.cts +0 -144
  90. package/@types/synchronizers/synchronizer-ws-server-simple/with-schemas/index.d.cts +0 -144
  91. package/@types/synchronizers/with-schemas/index.d.cts +0 -503
  92. package/@types/ui-react/index.d.cts +0 -16640
  93. package/@types/ui-react/with-schemas/index.d.cts +0 -17281
  94. package/@types/ui-react-dom/index.d.cts +0 -1862
  95. package/@types/ui-react-dom/with-schemas/index.d.cts +0 -1994
  96. package/@types/ui-react-inspector/index.d.cts +0 -79
  97. package/@types/ui-react-inspector/with-schemas/index.d.cts +0 -1985
  98. package/@types/with-schemas/index.d.cts +0 -17
@@ -1,1877 +0,0 @@
1
- /**
2
- * The persisters module of the TinyBase project provides a simple framework for
3
- * saving and loading Store and MergeableStore data, to and from different
4
- * destinations, or underlying storage types.
5
- *
6
- * Many entry points are provided (in separately installed modules), each of
7
- * which returns different types of Persister that can load and save a Store.
8
- * Between them, these allow you to store your TinyBase data locally, remotely,
9
- * to SQLite and PostgreSQL databases, and across synchronization boundaries
10
- * with CRDT frameworks.
11
- *
12
- * |Persister|Storage|Store|MergeableStore
13
- * |-|-|-|-|
14
- * |SessionPersister|Browser session storage|Yes|Yes
15
- * |LocalPersister|Browser local storage|Yes|Yes
16
- * |FilePersister|Local file (where possible)|Yes|Yes
17
- * |IndexedDbPersister|Browser IndexedDB|Yes|No
18
- * |RemotePersister|Remote server|Yes|No
19
- * |Sqlite3Persister|SQLite in Node, via [sqlite3](https://github.com/TryGhost/node-sqlite3)|Yes|Yes*
20
- * |SqliteWasmPersister|SQLite in a browser, via [sqlite-wasm](https://github.com/tomayac/sqlite-wasm)|Yes|Yes*
21
- * |ExpoSqlitePersister|SQLite in React Native, via [expo-sqlite](https://github.com/expo/expo/tree/main/packages/expo-sqlite)|Yes|Yes*
22
- * |PostgresPersister|PostgreSQL, via [postgres](https://github.com/porsager/postgres)|Yes|Yes*
23
- * |PglitePersister|PostgreSQL, via [PGlite](https://github.com/electric-sql/pglite)|Yes|Yes*
24
- * |CrSqliteWasmPersister|SQLite CRDTs, via [cr-sqlite-wasm](https://github.com/vlcn-io/cr-sqlite)|Yes|No
25
- * |ElectricSqlPersister|Electric SQL, via [electric-sql](https://github.com/electric-sql/electric)|Yes|No
26
- * |LibSqlPersister|LibSQL for Turso, via [libsql-client](https://github.com/tursodatabase/libsql-client-ts)|Yes|No
27
- * |PowerSyncPersister|PowerSync, via [powersync-sdk](https://github.com/powersync-ja/powersync-js)|Yes|No
28
- * |YjsPersister|Yjs CRDTs, via [yjs](https://github.com/yjs/yjs)|Yes|No
29
- * |AutomergePersister|Automerge CRDTs, via [automerge-repo](https://github.com/automerge/automerge-repo)|Yes|No
30
- * |PartyKitPersister|[PartyKit](https://www.partykit.io/), via the persister-partykit-server module|Yes|No|
31
- *
32
- * (*) Note that SQLite- and PostgreSQL-based Persisters can currently only
33
- * persist MergeableStore data when used with the JSON-based DpcJson mode, and
34
- * not when using the DpcTabular mode.
35
- *
36
- * Since persistence requirements can be different for every app, the
37
- * createCustomPersister function in this module can also be used to easily
38
- * create a fully customized way to save and load Store data.
39
- *
40
- * Similarly, the createCustomSqlitePersister function and
41
- * createCustomPostgreSqlPersister function can be used to build Persister objects
42
- * against SQLite and PostgreSQL SDKs (or forks) that are not already included
43
- * with TinyBase.
44
- * @see Persistence guides
45
- * @see Countries demo
46
- * @see Todo App demos
47
- * @see Drawing demo
48
- * @packageDocumentation
49
- * @module persisters
50
- * @since v1.0.0
51
- */
52
- import type {Id} from '../common/index.d.cts';
53
- import type {
54
- MergeableChanges,
55
- MergeableContent,
56
- MergeableStore,
57
- } from '../mergeable-store/index.d.cts';
58
- import type {Changes, Content, Store} from '../store/index.d.cts';
59
-
60
- /**
61
- * The Status enum is used to indicate whether a Persister is idle, or loading or
62
- * saving data.
63
- *
64
- * The enum is intended to be used to understand the status of the Persister in
65
- * conjunction with the getStatus and addStatusListener methods.
66
- *
67
- * Note that a Persister cannot be loading and saving data at the same time.
68
- * @category Lifecycle
69
- * @since v5.3.0
70
- */
71
- export const enum Status {
72
- /**
73
- * Indicates that the Persister is neither loading or saving data.
74
- * @category Enum
75
- * @since v5.3.0
76
- */
77
- Idle = 0,
78
- /**
79
- * Indicates that the Persister is loading data.
80
- * @category Enum
81
- * @since v5.3.0
82
- */
83
- Loading = 1,
84
- /**
85
- * Indicates that the Persister is saving data.
86
- * @category Enum
87
- * @since v5.3.0
88
- */
89
- Saving = 2,
90
- }
91
-
92
- /**
93
- * The Persists enum is used to indicate whether a Persister can support a
94
- * regular Store, a MergeableStore, or both.
95
- *
96
- * The enum is intended to be used by the author of a Persister to indicate
97
- * which types of store can be persisted. If you discover type errors when
98
- * trying to instantiate a Persister, it is most likely that you are passing in
99
- * an unsupported type of store.
100
- *
101
- * See the createCustomPersister method for an example of this enum being used.
102
- * @category Mergeable
103
- * @since v5.0.0
104
- */
105
- export const enum Persists {
106
- /**
107
- * Indicates that only a regular Store can be supported by a Persister.
108
- * @category Enum
109
- * @since v5.0.0
110
- */
111
- StoreOnly = 1,
112
- /**
113
- * Indicates that only a MergeableStore can be supported by a Persister.
114
- * @category Enum
115
- * @since v5.0.0
116
- */
117
- MergeableStoreOnly = 2,
118
- /**
119
- * Indicates that either a regular Store or a MergeableStore can be supported
120
- * by a Persister.
121
- * @category Enum
122
- * @since v5.0.0
123
- */
124
- StoreOrMergeableStore = 3,
125
- }
126
-
127
- /**
128
- * The PersistedStore type is a generic representation of the type of store
129
- * being handled by a Persister.
130
- *
131
- * Using the values of the Persists enum, the generic parameter indicates
132
- * whether the Persister is handling a regular Store, a MergeableStore, or
133
- * either.
134
- *
135
- * If the generic parameter is unspecified, the StoreOnly enum value is used,
136
- * meaning that PersistedStore is equivalent to a regular Store.
137
- * @category Mergeable
138
- * @since v5.0.0
139
- */
140
- export type PersistedStore<Persist extends Persists = Persists.StoreOnly> =
141
- Persist extends Persists.StoreOrMergeableStore
142
- ? Store | MergeableStore
143
- : Persist extends Persists.MergeableStoreOnly
144
- ? MergeableStore
145
- : Store;
146
-
147
- /**
148
- * The PersistedContent type is a generic representation of the content in the
149
- * type of store being handled by a Persister.
150
- *
151
- * Using the values of the Persists enum, the generic parameter indicates
152
- * whether the Persister is handling content from a regular Store (the Content
153
- * type), a MergeableStore (the MergeableContent type), or either (the union of
154
- * the two).
155
- *
156
- * If the generic parameter is unspecified, the StoreOnly enum value is used,
157
- * meaning that PersistedContent is equivalent to the Content type.
158
- * @category Mergeable
159
- * @since v5.0.0
160
- */
161
- export type PersistedContent<Persist extends Persists = Persists.StoreOnly> =
162
- Persist extends Persists.StoreOrMergeableStore
163
- ? Content | MergeableContent
164
- : Persist extends Persists.MergeableStoreOnly
165
- ? MergeableContent
166
- : Content;
167
-
168
- /**
169
- * The PersistedChanges type is a generic representation of changes made to the
170
- * type of store being handled by a Persister.
171
- *
172
- * Using the values of the Persists enum, the generic parameter indicates
173
- * whether the Persister is handling changes for a regular Store (the Changes
174
- * type), a MergeableStore (the MergeableChanges type), or either (the union of
175
- * the two).
176
- * @category Mergeable
177
- * @since v5.0.0
178
- */
179
- export type PersistedChanges<
180
- Persist extends Persists = Persists.StoreOnly,
181
- Hashed extends boolean = false,
182
- > = Persist extends Persists.StoreOrMergeableStore
183
- ? Changes | MergeableChanges<Hashed>
184
- : Persist extends Persists.MergeableStoreOnly
185
- ? MergeableChanges<Hashed>
186
- : Changes;
187
-
188
- /**
189
- * A PersisterListener is a generic representation of the callback that lets a
190
- * Persister inform the store that a change has happened to the underlying data.
191
- *
192
- * Using the values of the Persists enum, the generic parameter indicates
193
- * whether the Persister is handling content and changes from a regular Store, a
194
- * MergeableStore, or either.
195
- *
196
- * If the listener is called with the `changes` parameter, it will be used to
197
- * make an incremental change to the Store. If not, but the `content` parameter
198
- * is available, that will be used to make a wholesale change to the Store. If
199
- * neither are present, the content will be loaded using the Persister's load
200
- * method. Prior to v5.0, these parameters were callbacks and the overall type
201
- * was non-generic.
202
- * @param content If provided, this is a Content object from the the Persister
203
- * that will be used to immediately wholesale update the Store.
204
- * @param changes If provided, this is a Changes object from the the Persister
205
- * that will be used to immediately incrementally update the Store. This takes
206
- * priority over the content argument above if present.
207
- * @category Creation
208
- * @since v4.0.0
209
- */
210
- export type PersisterListener<Persist extends Persists = Persists.StoreOnly> = (
211
- content?: PersistedContent<Persist>,
212
- changes?: PersistedChanges<Persist>,
213
- ) => void;
214
-
215
- /**
216
- * The StatusListener type describes a function that is used to listen to
217
- * changes to the loading and saving status of the Persister.
218
- *
219
- * A StatusListener is provided when using the addStatusListener method. See
220
- * that method for specific examples.
221
- *
222
- * When called, a StatusListener is given a reference to the Persister and the
223
- * new Status: 0 means now idle, 1 means now loading, and 2 means now saving.
224
- * @param persister A reference to the Persister that changed.
225
- * @param status The new loading or saving Status.
226
- * @category Listener
227
- * @since v5.3.0
228
- */
229
- export type StatusListener<Persist extends Persists = Persists.StoreOnly> = (
230
- persister: Persister<Persist>,
231
- status: Status,
232
- ) => void;
233
-
234
- /**
235
- * The PersisterStats type describes the number of times a Persister object has
236
- * loaded or saved data.
237
- *
238
- * A PersisterStats object is returned from the getStats method.
239
- * @category Development
240
- * @since v1.0.0
241
- */
242
- export type PersisterStats = {
243
- /**
244
- * The number of times data has been loaded.
245
- * @category Stat
246
- * @since v1.0.0
247
- */
248
- loads: number;
249
- /**
250
- * The number of times data has been saved.
251
- * @category Stat
252
- * @since v1.0.0
253
- */
254
- saves: number;
255
- };
256
-
257
- /**
258
- * The DatabasePersisterConfig type describes the configuration of a
259
- * database-oriented Persister, such as those for SQLite and PostgreSQL.
260
- *
261
- * There are two modes for persisting a Store with a database:
262
- *
263
- * - A JSON serialization of the whole Store, which is stored in a single row of
264
- * a table (normally called `tinybase`) within the database. This is
265
- * configured by providing a DpcJson object.
266
- * - A tabular mapping of Table Ids to database table names (and vice-versa).
267
- * Values are stored in a separate special table (normally called
268
- * `tinybase_values`). This is configured by providing a DpcTabular object.
269
- *
270
- * Please see the DpcJson and DpcTabular type documentation for more detail on
271
- * each. If not specified otherwise, JSON serialization will be used for
272
- * persistence.
273
- *
274
- * Changes made to the database (outside of this Persister) are picked up
275
- * immediately if they are made via the same connection or library that it is
276
- * using. If the database is being changed by another client, the Persister
277
- * needs to poll for changes. Hence both configuration types also contain an
278
- * `autoLoadIntervalSeconds` property which indicates how often it should do
279
- * that. This defaults to 1 second.
280
- *
281
- * Note that all the nested types within this type have a 'Dpc' prefix, short
282
- * for 'DatabasePersisterConfig'.
283
- * @example
284
- * When applied to a database Persister, this DatabasePersisterConfig will load
285
- * and save a JSON serialization from and to a table called `my_tinybase`,
286
- * polling the database every 2 seconds. See DpcJson for more details on these
287
- * settings.
288
- *
289
- * ```js
290
- * import type {DatabasePersisterConfig} from 'tinybase';
291
- *
292
- * export const databasePersisterConfig: DatabasePersisterConfig = {
293
- * mode: 'json',
294
- * storeTableName: 'my_tinybase',
295
- * autoLoadIntervalSeconds: 2,
296
- * };
297
- * ```
298
- * @example
299
- * When applied to a database Persister, this DatabasePersisterConfig will load
300
- * and save tabular data from and to tables specified in the `load` and `save`
301
- * mappings. See DpcTabular for more details on these settings.
302
- *
303
- * ```js
304
- * import type {DatabasePersisterConfig} from 'tinybase';
305
- *
306
- * export const databasePersisterConfig: DatabasePersisterConfig = {
307
- * mode: 'tabular',
308
- * tables: {
309
- * load: {petsInDb: 'pets', speciesInDb: 'species'},
310
- * save: {pets: 'petsInDb', species: 'speciesInDb'},
311
- * },
312
- * };
313
- * ```
314
- * @category Configuration
315
- * @since v4.0.0
316
- */
317
- export type DatabasePersisterConfig = DpcJson | DpcTabular;
318
-
319
- /**
320
- * The DpcJson type describes the configuration of a database-oriented Persister
321
- * operating in serialized JSON mode.
322
- *
323
- * One setting is the `storeTableName` property, which indicates the name of a
324
- * table in the database which will be used to serialize the Store content into.
325
- * It defaults to `tinybase`.
326
- *
327
- * That table in the database will be given two columns: a primary key column
328
- * called `_id`, and one called `store`. (These column names can be changed
329
- * using the `rowIdColumnName` and `storeColumnName` settings). The Persister
330
- * will place a single row in this table with `_` in the `_id` column, and the
331
- * JSON serialization in the `store` column, something like the following.
332
- *
333
- * ```
334
- * > SELECT * FROM tinybase;
335
- * +-----+-----------------------------------------------------+
336
- * | _id | store |
337
- * +-----+-----------------------------------------------------+
338
- * | _ | [{"pets":{"fido":{"species":"dog"}}},{"open":true}] |
339
- * +-----+-----------------------------------------------------+
340
- * ```
341
- *
342
- * The 'Dpc' prefix indicates that this type is used within the
343
- * DatabasePersisterConfig type.
344
- * @example
345
- * When applied to a database Persister, this DatabasePersisterConfig will load
346
- * and save a JSON serialization from and to a table called `tinybase_json`.
347
- *
348
- * ```js
349
- * import type {DatabasePersisterConfig} from 'tinybase';
350
- *
351
- * export const databasePersisterConfig: DatabasePersisterConfig = {
352
- * mode: 'json',
353
- * storeTableName: 'tinybase_json',
354
- * };
355
- * ```
356
- * @category Configuration
357
- * @since v4.0.0
358
- */
359
- export type DpcJson = {
360
- /**
361
- * The mode to be used for persisting the Store to the database, in this case
362
- * JSON serialization. See the DpcTabular type for the alternative tabular
363
- * mapping mode.
364
- * @category Configuration
365
- * @since v4.0.0
366
- */
367
- mode: 'json';
368
- /**
369
- * An optional string which indicates the name of a table in the database
370
- * which will be used to serialize the Store content into. It defaults to
371
- * `tinybase`.
372
- * @category Configuration
373
- * @since v4.0.0
374
- */
375
- storeTableName?: string;
376
- /**
377
- * The optional name of the column in the database table that will be used as
378
- * the Id for the Store, defaulting to '_id', since v5.0.
379
- * @category Configuration
380
- * @since v4.0.0
381
- */
382
- storeIdColumnName?: string;
383
- /**
384
- * The optional name of the column in the database table that will be used for
385
- * the JSON of the Store, defaulting to 'store', since v5.0.
386
- * @category Configuration
387
- * @since v4.0.0
388
- */
389
- storeColumnName?: string;
390
- /**
391
- * How often the Persister should poll the database for any changes made to it
392
- * by other clients, defaulting to 1 second.
393
- * @category Configuration
394
- * @since v4.0.0
395
- */
396
- autoLoadIntervalSeconds?: number;
397
- };
398
-
399
- /**
400
- * The DpcTabular type describes the configuration of a database-oriented
401
- * Persister that is operating in tabular mapping mode.
402
- *
403
- * This configuration can only be used when the Persister is persisting a
404
- * regular Store. For those database-oriented Persister types that support
405
- * MergeableStore data, you will need to use JSON-serialization, es described in
406
- * the DpcJson section.
407
- *
408
- * It is important to note that both the tabular mapping in ('save') and out
409
- * ('load') of an underlying database are disabled by default. This is to ensure
410
- * that if you pass in an existing populated database you don't run the
411
- * immediate risk of corrupting or losing all your data.
412
- *
413
- * This configuration therefore takes a `tables` property object (with child
414
- * `load` and `save` property objects) and a `values` property object. These
415
- * indicate how you want to load and save Tables and Values respectively. At
416
- * least one of these two properties are required for the Persister to do
417
- * anything!
418
- *
419
- * Note that if you are planning to both load from and save to a database, it is
420
- * important to make sure that the load and save table mappings are symmetrical.
421
- * For example, consider the following.
422
- *
423
- * ```js
424
- * import type {DatabasePersisterConfig} from 'tinybase';
425
- *
426
- * export const databasePersisterConfig: DatabasePersisterConfig = {
427
- * mode: 'tabular',
428
- * tables: {
429
- * load: {petsInDb: 'pets', speciesInDb: 'species'},
430
- * save: {pets: 'petsInDb', species: 'speciesInDb'},
431
- * },
432
- * };
433
- * ```
434
- *
435
- * See the documentation for the DpcTabularLoad, DpcTabularSave, and
436
- * DpcTabularValues types for more details on how to configure the tabular
437
- * mapping mode.
438
- *
439
- * Columns in SQLite database have no type, and so in this mode, the table can
440
- * contain strings and numbers for Cells and Values, just as TinyBase does.
441
- * Booleans, unfortunately, are stored as 0 or 1 in SQLite, and cannot be
442
- * distinguished from numbers.
443
- *
444
- * In PostgreSQL databases, all Cell and Value columns are expected to be typed
445
- * as `text`, and the strings, booleans, and numbers are all JSON-encoded by the
446
- * Persister.
447
- *
448
- * The 'Dpc' prefix indicates that this type is used within the
449
- * DatabasePersisterConfig type.
450
- * @example
451
- * When applied to a database Persister, this DatabasePersisterConfig will load
452
- * and save Tables data from and to tables specified in the `load` and `save`
453
- * mappings, and Values data from and to a table called `my_tinybase_values`.
454
- *
455
- * ```js
456
- * import type {DatabasePersisterConfig} from 'tinybase';
457
- *
458
- * export const databasePersisterConfig: DatabasePersisterConfig = {
459
- * mode: 'tabular',
460
- * tables: {
461
- * load: {petsInDb: 'pets', speciesInDb: 'species'},
462
- * save: {pets: 'petsInDb', species: 'speciesInDb'},
463
- * },
464
- * values: {
465
- * load: true,
466
- * save: true,
467
- * tableName: 'my_tinybase_values',
468
- * },
469
- * };
470
- * ```
471
- * @category Configuration
472
- * @since v4.0.0
473
- */
474
- export type DpcTabular = {
475
- /**
476
- * The mode to be used for persisting the Store to the database, in this case
477
- * tabular mapping. See the DpcJson type for the alternative JSON
478
- * serialization mode.
479
- * @category Configuration
480
- * @since v4.0.0
481
- */
482
- mode: 'tabular';
483
- /**
484
- * The settings for how the Store Tables are mapped to and from the database.
485
- * @category Configuration
486
- * @since v4.0.0
487
- */
488
- tables?: {
489
- /**
490
- * The settings for how the database tables are mapped into the Store Tables
491
- * when loading.
492
- * @category Configuration
493
- * @since v4.0.0
494
- */
495
- load?: DpcTabularLoad;
496
- /**
497
- * The settings for how the Store Tables are mapped out to the database
498
- * tables when saving.
499
- * @category Configuration
500
- * @since v4.0.0
501
- */
502
- save?: DpcTabularSave;
503
- };
504
- /**
505
- * The settings for how the Store Values are mapped to and from the database.
506
- * @category Configuration
507
- * @since v4.0.0
508
- */
509
- values?: DpcTabularValues;
510
- /**
511
- * How often the Persister should poll the database for any changes made to it
512
- * by other clients, defaulting to 1 second.
513
- * @category Configuration
514
- * @since v4.0.0
515
- */
516
- autoLoadIntervalSeconds?: number;
517
- };
518
-
519
- /**
520
- * The DpcTabularLoad type describes the configuration for loading Tables in a
521
- * database-oriented Persister that is operating in tabular mode.
522
- *
523
- * It is an object where each key is a name of a database table, and the value
524
- * is a child configuration object for how that table should be loaded into the
525
- * Store. The properties of the child configuration object are:
526
- *
527
- * ||Type|Description|
528
- * |-|-|-|
529
- * |`tableId`|Id|The Id of the Store Table into which data from this database table should be loaded.|
530
- * |`rowIdColumnName?`|string|The optional name of the column in the database table that will be used as the Row Ids in the Store Table, defaulting to '_id'.|
531
- *
532
- * As a shortcut, if you do not need to specify a custom `rowIdColumnName`, you
533
- * can simply provide the Id of the Store Table instead of the whole object.
534
- *
535
- * The 'Dpc' prefix indicates that this type is used within the
536
- * DatabasePersisterConfig type.
537
- * @example
538
- * When applied to a database Persister, this DatabasePersisterConfig will load
539
- * the data of two database tables (called 'petsInDb' and 'speciesInDb') into
540
- * two Store Tables (called 'pets' and 'species'). One has a column for the Row
541
- * Id called 'id' and the other defaults it to '_id'.
542
- *
543
- * ```js
544
- * import type {DatabasePersisterConfig} from 'tinybase';
545
- *
546
- * export const databasePersisterConfig: DatabasePersisterConfig = {
547
- * mode: 'tabular',
548
- * tables: {
549
- * load: {
550
- * petsInDb: {tableId: 'pets', rowIdColumnName: 'id'},
551
- * speciesInDb: 'species',
552
- * },
553
- * },
554
- * };
555
- * ```
556
- *
557
- * Imagine database tables that look like this:
558
- *
559
- * ```
560
- * > SELECT * FROM petsInDb;
561
- * +-------+---------+-------+
562
- * | id | species | color |
563
- * +-------+---------+-------+
564
- * | fido | dog | brown |
565
- * | felix | cat | black |
566
- * +-------+---------+-------+
567
- *
568
- * > SELECT * FROM speciesInDb;
569
- * +------+-------+
570
- * | _id | price |
571
- * +------+-------+
572
- * | dog | 5 |
573
- * | cat | 4 |
574
- * +------+-------+
575
- * ```
576
- *
577
- * With the configuration above, this will load into a Store with Tables that
578
- * look like this:
579
- *
580
- * ```json
581
- * {
582
- * "pets": {
583
- * "fido": {"species": "dog", "color": "brown"},
584
- * "felix": {"species": "cat", "color": "black"},
585
- * },
586
- * "species": {
587
- * "dog": {"price": 5},
588
- * "cat": {"price": 4},
589
- * },
590
- * }
591
- * ```
592
- *
593
- * The example above represents what happens with a SQLite Persister. In
594
- * PostgreSQL databases, all Cell and Value columns are expected to be
595
- * typed as `text`, and the strings, booleans, and numbers would be JSON-encoded
596
- * if you queried them.
597
- * @category Configuration
598
- * @since v4.0.0
599
- */
600
- export type DpcTabularLoad = {
601
- [tableName: string]:
602
- | {
603
- /**
604
- * The Id of the Store Table into which data from this database table
605
- * should be loaded.
606
- * @category Configuration
607
- * @since v4.0.0
608
- */
609
- tableId: Id;
610
- /**
611
- * The optional name of the column in the database table that will be
612
- * used as the Row Ids in the Store Table, defaulting to '_id'.
613
- * @category Configuration
614
- * @since v4.0.0
615
- */
616
- rowIdColumnName?: string;
617
- }
618
- | Id;
619
- };
620
-
621
- /**
622
- * The DpcTabularSave type describes the configuration for saving Tables in a
623
- * database-oriented Persister that is operating in tabular mode.
624
- *
625
- * It is an object where each key is an Id of a Store Table, and the value is a
626
- * child configuration object for how that Table should be saved out to the
627
- * database. The properties of the child configuration object are:
628
- *
629
- * ||Type|Description|
630
- * |-|-|-|
631
- * |`tableName`|string|The name of the database table out to which the Store Table should be saved.|
632
- * |`rowIdColumnName?`|string|The optional name of the column in the database table that will be used to save the Row Ids from the Store Table, defaulting to '_id'.|
633
- * |`deleteEmptyColumns?`|boolean|Whether columns in the database table will be removed if they are empty in the Store Table, defaulting to false.|
634
- * |`deleteEmptyTable?`|boolean|Whether tables in the database will be removed if the Store Table is empty, defaulting to false.|
635
- *
636
- * As a shortcut, if you do not need to specify a custom `rowIdColumnName`, or
637
- * enable the `deleteEmptyColumns` or `deleteEmptyTable` settings, you can
638
- * simply provide the name of the database table instead of the whole object.
639
- *
640
- * `deleteEmptyColumns` and `deleteEmptyTable` only have a guaranteed effect
641
- * when an explicit call is made to the Persister's save method. Columns and
642
- * tables will not necessarily be removed when the Persister is incrementally
643
- * 'autoSaving', due to performance reasons. If you want to be sure that your
644
- * database table matches a TinyBase Table without any extraneous columns,
645
- * simply call the save method at an idle moment.
646
- *
647
- * The 'Dpc' prefix indicates that this type is used within the
648
- * DatabasePersisterConfig type.
649
- * @example
650
- * When applied to a database Persister, this DatabasePersisterConfig will save
651
- * the data of two Store Tables (called 'pets' and 'species') into two database
652
- * tables (called 'petsInDb' and 'speciesInDb'). One has a column for the Row
653
- * Id called 'id' and will delete columns and the whole table if empty, the
654
- * other defaults to '_id' and will not delete columns or the whole table if
655
- * empty.
656
- *
657
- * ```js
658
- * import type {DatabasePersisterConfig} from 'tinybase';
659
- *
660
- * export const databasePersisterConfig: DatabasePersisterConfig = {
661
- * mode: 'tabular',
662
- * tables: {
663
- * save: {
664
- * pets: {
665
- * tableName: 'petsInDb',
666
- * deleteEmptyColumns: true,
667
- * deleteEmptyTable: true,
668
- * },
669
- * species: 'speciesInDb',
670
- * },
671
- * },
672
- * };
673
- * ```
674
- *
675
- * Imagine a Store with Tables that look like this:
676
- *
677
- * ```json
678
- * {
679
- * "pets": {
680
- * "fido": {"species": "dog", "color": "brown"},
681
- * "felix": {"species": "cat", "color": "black"},
682
- * },
683
- * "species": {
684
- * "dog": {"price": 5},
685
- * "cat": {"price": 4},
686
- * },
687
- * }
688
- * ```
689
- *
690
- * With the configuration above, this will save out to a database with tables
691
- * that look like this:
692
- *
693
- * ```
694
- * > SELECT * FROM petsInDb;
695
- * +-------+---------+-------+
696
- * | id | species | color |
697
- * +-------+---------+-------+
698
- * | fido | dog | brown |
699
- * | felix | cat | black |
700
- * +-------+---------+-------+
701
- *
702
- * > SELECT * FROM speciesInDb;
703
- * +------+-------+
704
- * | _id | price |
705
- * +------+-------+
706
- * | dog | 5 |
707
- * | cat | 4 |
708
- * +------+-------+
709
- * ```
710
- * The example above represents what happens with a SQLite Persister. In
711
- * PostgreSQL databases, all Cell and Value columns are expected to be
712
- * typed as `text`, and the strings, booleans, and numbers would be JSON-encoded
713
- * if you queried them.
714
- * @category Configuration
715
- * @since v4.0.0
716
- */
717
- export type DpcTabularSave = {
718
- [tableId: Id]:
719
- | {
720
- /**
721
- * The name of the database table out to which the Store Table should be
722
- * saved.
723
- * @category Configuration
724
- * @since v4.0.0
725
- */
726
- tableName: string;
727
- /**
728
- * The optional name of the column in the database table that will be
729
- * used to save the Row Ids from the Store Table, defaulting to '_id'.
730
- * @category Configuration
731
- * @since v4.0.0
732
- */
733
- rowIdColumnName?: string;
734
- /**
735
- * Whether columns in the database table will be removed if they are
736
- * empty in the Store Table, defaulting to false.
737
- * @category Configuration
738
- * @since v4.0.0
739
- */
740
- deleteEmptyColumns?: boolean;
741
- /**
742
- * Whether tables in the database will be removed if the Store Table is
743
- * empty, defaulting to false.
744
- * @category Configuration
745
- * @since v4.0.0
746
- */
747
- deleteEmptyTable?: boolean;
748
- }
749
- | string;
750
- };
751
-
752
- /**
753
- * The DpcTabularValues type describes the configuration for handling Values in
754
- * a database-oriented Persister that is operating in tabular mode.
755
- *
756
- * Note that both loading and saving of Values from and to the database are
757
- * disabled by default.
758
- *
759
- * The 'Dpc' prefix indicates that this type is used within the
760
- * DatabasePersisterConfig type.
761
- * @example
762
- * When applied to a database Persister, this DatabasePersisterConfig will load
763
- * and save the data of a Store's Values into a database
764
- * table called 'my_tinybase_values'.
765
- *
766
- * ```js
767
- * import type {DatabasePersisterConfig} from 'tinybase';
768
- *
769
- * export const databasePersisterConfig: DatabasePersisterConfig = {
770
- * mode: 'tabular',
771
- * values: {
772
- * load: true,
773
- * save: true,
774
- * tableName: 'my_tinybase_values',
775
- * },
776
- * };
777
- * ```
778
- * @category Configuration
779
- * @since v4.0.0
780
- */
781
- export type DpcTabularValues = {
782
- /**
783
- * Whether Store Values will be loaded from a database table.
784
- * @category Configuration
785
- * @since v4.0.0
786
- */
787
- load?: boolean;
788
- /**
789
- * Whether Store Values will be saved to a database table.
790
- * @category Configuration
791
- * @since v4.0.0
792
- */
793
- save?: boolean;
794
- /**
795
- * The optional name of the database table from and to which the Store Values
796
- * should be loaded or saved, defaulting to `tinybase_values`.
797
- * @category Configuration
798
- * @since v4.0.0
799
- */
800
- tableName?: string;
801
- };
802
-
803
- /**
804
- * A Persister object lets you save and load Store data to and from different
805
- * locations, or underlying storage types.
806
- *
807
- * This is useful for preserving Store or MergeableStore data between browser
808
- * sessions or reloads, saving or loading browser state to or from a server, or
809
- * saving Store data to disk in a environment with filesystem access.
810
- *
811
- * Creating a Persister depends on the choice of underlying storage where the
812
- * data is to be stored. Options include the createSessionPersister function,
813
- * the createLocalPersister function, the createRemotePersister function, and
814
- * the createFilePersister function, as just simple examples. The
815
- * createCustomPersister function can also be used to easily create a fully
816
- * customized way to save and load Store data.
817
- *
818
- * Using the values of the Persists enum, the generic parameter to the Persister
819
- * indicates whether it can handle a regular Store, a MergeableStore, or either.
820
- * Consult the table in the overall persisters module documentation to see
821
- * current support for each. The different levels of support are also described
822
- * for each of the types of Persister themselves.
823
- *
824
- * A Persister lets you explicit save or load data, with the save method and the
825
- * load method respectively. These methods are both asynchronous (since the
826
- * underlying data storage may also be) and return promises. As a result you
827
- * should use the `await` keyword to call them in a way that guarantees
828
- * subsequent execution order.
829
- *
830
- * When you don't want to deal with explicit persistence operations, a Persister
831
- * object also provides automatic saving and loading. Automatic saving listens
832
- * for changes to the Store and persists the data immediately. Automatic loading
833
- * listens (or polls) for changes to the persisted data and reflects those
834
- * changes in the Store.
835
- *
836
- * You can start automatic saving or loading with the startAutoSave method and
837
- * startAutoLoad method. Both are asynchronous since they will do an immediate
838
- * save and load before starting to listen for subsequent changes. You can stop
839
- * the behavior with the stopAutoSave method and stopAutoLoad method (which are
840
- * synchronous).
841
- *
842
- * You may often want to have both automatic saving and loading of a Store so
843
- * that changes are constantly synchronized (allowing basic state preservation
844
- * between browser tabs, for example). The framework has some basic provisions
845
- * to prevent race conditions - for example it will not attempt to save data if
846
- * it is currently loading it and vice-versa - and will sequentially schedule
847
- * methods that could cause race conditions.
848
- *
849
- * That said, be aware that you should always comprehensively test your
850
- * persistence strategy to understand the opportunity for data loss (in the case
851
- * of trying to save data to a server under poor network conditions, for
852
- * example).
853
- *
854
- * To help debug such issues, since v4.0.4, the create methods for all Persister
855
- * objects take an optional `onIgnoredError` argument. This is a handler for the
856
- * errors that the Persister would otherwise ignore when trying to save or load
857
- * data (such as when handling corrupted stored data). It's recommended you use
858
- * this for debugging persistence issues, but only in a development environment.
859
- * Database-based Persister objects also take an optional `onSqlCommand`
860
- * argument for logging commands and queries made to the underlying database.
861
- * @example
862
- * This example creates a Store, persists it to the browser's session storage as
863
- * a JSON string, changes the persisted data, updates the Store from it, and
864
- * finally destroys the Persister again.
865
- *
866
- * ```js
867
- * import {createStore} from 'tinybase';
868
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
869
- *
870
- * const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
871
- * const persister = createSessionPersister(store, 'pets');
872
- *
873
- * await persister.save();
874
- * console.log(sessionStorage.getItem('pets'));
875
- * // -> '[{"pets":{"fido":{"species":"dog"}}},{}]'
876
- *
877
- * sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
878
- * await persister.load();
879
- * console.log(store.getTables());
880
- * // -> {pets: {toto: {species: 'dog'}}}
881
- *
882
- * persister.destroy();
883
- * sessionStorage.clear();
884
- * ```
885
- * @example
886
- * This example creates a Store, and automatically saves and loads it to the
887
- * browser's session storage as a JSON string. Changes to the Store data, or the
888
- * persisted data (implicitly firing a StorageEvent), are reflected accordingly.
889
- *
890
- * ```js
891
- * import {createStore} from 'tinybase';
892
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
893
- *
894
- * const store = createStore();
895
- * const persister = createSessionPersister(store, 'pets');
896
- *
897
- * await persister.startAutoLoad([{pets: {fido: {species: 'dog'}}}, {}]);
898
- * await persister.startAutoSave();
899
- *
900
- * store.setTables({pets: {felix: {species: 'cat'}}});
901
- * // ...
902
- * console.log(sessionStorage.getItem('pets'));
903
- * // -> '[{"pets":{"felix":{"species":"cat"}}},{}]'
904
- *
905
- * // In another browser tab:
906
- * sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
907
- * // -> StorageEvent('storage', {storageArea: sessionStorage, key: 'pets'})
908
- *
909
- * // ...
910
- * console.log(store.getTables());
911
- * // -> {pets: {toto: {species: 'dog'}}}
912
- *
913
- * persister.destroy();
914
- * sessionStorage.clear();
915
- * ```
916
- * @category Persister
917
- * @since v1.0.0
918
- */
919
- export interface Persister<Persist extends Persists = Persists.StoreOnly> {
920
- //
921
- /**
922
- * The load method gets persisted data from storage, and loads it into the
923
- * Store with which the Persister is associated, once.
924
- *
925
- * The optional parameter allows you to specify what the initial content for
926
- * the Store will be if there is nothing currently persisted or if the load
927
- * fails (for example when the Persister is remote and the environment is
928
- * offline). This allows you to fallback or instantiate a Store whether it's
929
- * loading from previously persisted storage or being run for the first time.
930
- * Since v5.4.2, this parameter can also be a function that returns the
931
- * content.
932
- *
933
- * This method is asynchronous because the persisted data may be on a remote
934
- * machine or a filesystem. Even for those storage types that are synchronous
935
- * (like browser storage) it is still recommended that you `await` calls to
936
- * this method or handle the return type natively as a Promise.
937
- * @param initialContent An optional Content object used when the underlying
938
- * storage has not previously been populated.
939
- * @returns A Promise containing a reference to the Persister object.
940
- * @example
941
- * This example creates an empty Store, and loads data into it from the
942
- * browser's session storage, which for the purposes of this example has been
943
- * previously populated.
944
- *
945
- * ```js
946
- * import {createStore} from 'tinybase';
947
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
948
- *
949
- * sessionStorage.setItem('pets', '[{"pets":{"fido":{"species":"dog"}}},{}]');
950
- *
951
- * const store = createStore();
952
- * const persister = createSessionPersister(store, 'pets');
953
- *
954
- * await persister.load();
955
- * console.log(store.getTables());
956
- * // -> {pets: {fido: {species: 'dog'}}}
957
- *
958
- * sessionStorage.clear();
959
- * ```
960
- * @example
961
- * This example creates an empty Store, and loads data into it from the
962
- * browser's session storage, which is at first empty, so the optional
963
- * parameter is used. The second time the load method is called, data has
964
- * previously been persisted and instead, that is loaded.
965
- *
966
- * ```js
967
- * import {createStore} from 'tinybase';
968
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
969
- *
970
- * const store = createStore();
971
- * const persister = createSessionPersister(store, 'pets');
972
- *
973
- * await persister.load([{pets: {fido: {species: 'dog'}}}, {}]);
974
- * console.log(store.getTables());
975
- * // -> {pets: {fido: {species: 'dog'}}}
976
- *
977
- * sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
978
- * await persister.load({pets: {fido: {species: 'dog'}}});
979
- * console.log(store.getTables());
980
- * // -> {pets: {toto: {species: 'dog'}}}
981
- *
982
- * sessionStorage.clear();
983
- * ```
984
- * @category Load
985
- * @since v1.0.0
986
- */
987
- load(initialContent?: Content | (() => Content)): Promise<this>;
988
-
989
- /**
990
- * The startAutoLoad method gets persisted data from storage, and loads it
991
- * into the Store with which the Persister is associated, once, and then
992
- * continuously.
993
- *
994
- * The optional parameter allows you to specify what the initial content for
995
- * the Store will be if there is nothing currently persisted or if the load
996
- * fails (for example when the Persister is remote and the environment is
997
- * offline). This allows you to fallback or instantiate a Store whether it's
998
- * loading from previously persisted storage or being run for the first time.
999
- * Since v5.4.2, this parameter can also be a function that returns the
1000
- * content.
1001
- *
1002
- * This method first runs a single call to the load method to ensure the data
1003
- * is in sync with the persisted storage. It then continues to watch for
1004
- * changes to the underlying data (either through events or polling, depending
1005
- * on the storage type), automatically loading the data into the Store.
1006
- *
1007
- * This method is asynchronous because it starts by making a single call to
1008
- * the asynchronous load method. Even for those storage types that are
1009
- * synchronous (like browser storage) it is still recommended that you `await`
1010
- * calls to this method or handle the return type natively as a Promise.
1011
- * @param initialContent An optional Content object used when the underlying
1012
- * storage has not previously been populated.
1013
- * @returns A Promise containing a reference to the Persister object.
1014
- * @example
1015
- * This example creates an empty Store, and loads data into it from the
1016
- * browser's session storage, which at first is empty (so the `initialTables`
1017
- * parameter is used). Subsequent changes to the underlying storage are then
1018
- * reflected in the Store (in this case through detection of StorageEvents
1019
- * from session storage changes made in another browser tab).
1020
- *
1021
- * ```js
1022
- * import {createStore} from 'tinybase';
1023
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1024
- *
1025
- * const store = createStore();
1026
- * const persister = createSessionPersister(store, 'pets');
1027
- *
1028
- * await persister.startAutoLoad([{pets: {fido: {species: 'dog'}}}, {}]);
1029
- * console.log(store.getTables());
1030
- * // -> {pets: {fido: {species: 'dog'}}}
1031
- *
1032
- * // In another browser tab:
1033
- * sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
1034
- * // -> StorageEvent('storage', {storageArea: sessionStorage, key: 'pets'})
1035
- *
1036
- * // ...
1037
- * console.log(store.getTables());
1038
- * // -> {pets: {toto: {species: 'dog'}}}
1039
- *
1040
- * persister.destroy();
1041
- * sessionStorage.clear();
1042
- * ```
1043
- * @category Load
1044
- * @since v1.0.0
1045
- */
1046
- startAutoLoad(initialContent?: Content | (() => Content)): Promise<this>;
1047
-
1048
- /**
1049
- * The stopAutoLoad method stops the automatic loading of data from storage
1050
- * previously started with the startAutoLoad method.
1051
- *
1052
- * If the Persister is not currently set to automatically load, this method
1053
- * has no effect.
1054
- * @returns A reference to the Persister object.
1055
- * @example
1056
- * This example creates an empty Store, and starts automatically loading data
1057
- * into it from the browser's session storage. Once the automatic loading is
1058
- * stopped, subsequent changes are not reflected in the Store.
1059
- *
1060
- * ```js
1061
- * import {createStore} from 'tinybase';
1062
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1063
- *
1064
- * const store = createStore();
1065
- * const persister = createSessionPersister(store, 'pets');
1066
- * await persister.startAutoLoad();
1067
- *
1068
- * // In another browser tab:
1069
- * sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
1070
- * // -> StorageEvent('storage', {storageArea: sessionStorage, key: 'pets'})
1071
- * // ...
1072
- * console.log(store.getTables());
1073
- * // -> {pets: {toto: {species: 'dog'}}}
1074
- *
1075
- * persister.stopAutoLoad();
1076
- *
1077
- * // In another browser tab:
1078
- * sessionStorage.setItem(
1079
- * 'pets',
1080
- * '[{"pets":{"felix":{"species":"cat"}}},{}]',
1081
- * );
1082
- * // -> StorageEvent('storage', {storageArea: sessionStorage, key: 'pets'})
1083
- * // ...
1084
- * console.log(store.getTables());
1085
- * // -> {pets: {toto: {species: 'dog'}}}
1086
- * // Storage change has not been automatically loaded.
1087
- *
1088
- * persister.destroy();
1089
- * sessionStorage.clear();
1090
- * ```
1091
- * @category Load
1092
- * @since v1.0.0
1093
- */
1094
- stopAutoLoad(): this;
1095
-
1096
- /**
1097
- * The isAutoLoading method lets you find out if the Persister is currently
1098
- * automatically loading its content.
1099
- * @returns A boolean indicating whether the Persister is currently
1100
- * autoLoading.
1101
- * @example
1102
- * This example creates a Persister and queries whether it is autoLoading.
1103
- *
1104
- * ```js
1105
- * import {createStore} from 'tinybase';
1106
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1107
- *
1108
- * const persister = createSessionPersister(createStore(), 'pets');
1109
- *
1110
- * console.log(persister.isAutoLoading());
1111
- * // -> false
1112
- *
1113
- * await persister.startAutoLoad();
1114
- * console.log(persister.isAutoLoading());
1115
- * // -> true
1116
- *
1117
- * await persister.stopAutoLoad();
1118
- * console.log(persister.isAutoLoading());
1119
- * // -> false
1120
- * ```
1121
- * @category Load
1122
- * @since v5.0.0
1123
- */
1124
- isAutoLoading(): boolean;
1125
-
1126
- /**
1127
- * The save method takes data from the Store with which the Persister is
1128
- * associated and persists it into storage, once.
1129
- *
1130
- * This method is asynchronous because the persisted data may be on a remote
1131
- * machine or a filesystem. Even for those storage types that are synchronous
1132
- * (like browser storage) it is still recommended that you `await` calls to
1133
- * this method or handle the return type natively as a Promise.
1134
- * @returns A Promise containing a reference to the Persister object.
1135
- * @example
1136
- * This example creates a Store with some data, and saves into the browser's
1137
- * session storage.
1138
- *
1139
- * ```js
1140
- * import {createStore} from 'tinybase';
1141
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1142
- *
1143
- * const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
1144
- * const persister = createSessionPersister(store, 'pets');
1145
- *
1146
- * await persister.save();
1147
- * console.log(sessionStorage.getItem('pets'));
1148
- * // -> '[{"pets":{"fido":{"species":"dog"}}},{}]'
1149
- *
1150
- * persister.destroy();
1151
- * sessionStorage.clear();
1152
- * ```
1153
- * @category Save
1154
- * @since v1.0.0
1155
- */
1156
- save(): Promise<this>;
1157
-
1158
- /**
1159
- * The save method takes data from the Store with which the Persister is
1160
- * associated and persists it into storage, once, and then continuously.
1161
- *
1162
- * This method first runs a single call to the save method to ensure the data
1163
- * is in sync with the persisted storage. It then continues to watch for
1164
- * changes to the Store, automatically saving the data to storage.
1165
- *
1166
- * This method is asynchronous because it starts by making a single call to
1167
- * the asynchronous save method. Even for those storage types that are
1168
- * synchronous (like browser storage) it is still recommended that you `await`
1169
- * calls to this method or handle the return type natively as a Promise.
1170
- * @returns A Promise containing a reference to the Persister object.
1171
- * @example
1172
- * This example creates a Store with some data, and saves into the browser's
1173
- * session storage. Subsequent changes to the Store are then automatically
1174
- * saved to the underlying storage.
1175
- *
1176
- * ```js
1177
- * import {createStore} from 'tinybase';
1178
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1179
- *
1180
- * const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
1181
- * const persister = createSessionPersister(store, 'pets');
1182
- *
1183
- * await persister.startAutoSave();
1184
- * console.log(sessionStorage.getItem('pets'));
1185
- * // -> '[{"pets":{"fido":{"species":"dog"}}},{}]'
1186
- *
1187
- * store.setTables({pets: {toto: {species: 'dog'}}});
1188
- * // ...
1189
- * console.log(sessionStorage.getItem('pets'));
1190
- * // -> '[{"pets":{"toto":{"species":"dog"}}},{}]'
1191
- *
1192
- * sessionStorage.clear();
1193
- * ```
1194
- * @category Save
1195
- * @since v1.0.0
1196
- */
1197
- startAutoSave(): Promise<this>;
1198
-
1199
- /**
1200
- * The stopAutoSave method stops the automatic save of data to storage
1201
- * previously started with the startAutoSave method.
1202
- *
1203
- * If the Persister is not currently set to automatically save, this method
1204
- * has no effect.
1205
- * @returns A reference to the Persister object.
1206
- * @example
1207
- * This example creates a Store with some data, and saves into the browser's
1208
- * session storage. Subsequent changes to the Store are then automatically
1209
- * saved to the underlying storage. Once the automatic saving is
1210
- * stopped, subsequent changes are not reflected.
1211
- *
1212
- * ```js
1213
- * import {createStore} from 'tinybase';
1214
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1215
- *
1216
- * const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
1217
- * const persister = createSessionPersister(store, 'pets');
1218
- * await persister.startAutoSave();
1219
- *
1220
- * store.setTables({pets: {toto: {species: 'dog'}}});
1221
- * // ...
1222
- * console.log(sessionStorage.getItem('pets'));
1223
- * // -> '[{"pets":{"toto":{"species":"dog"}}},{}]'
1224
- *
1225
- * persister.stopAutoSave();
1226
- *
1227
- * store.setTables({pets: {felix: {species: 'cat'}}});
1228
- * // ...
1229
- * console.log(sessionStorage.getItem('pets'));
1230
- * // -> '[{"pets":{"toto":{"species":"dog"}}},{}]'
1231
- * // Store change has not been automatically saved.
1232
- *
1233
- * sessionStorage.clear();
1234
- * ```
1235
- * @category Save
1236
- * @since v1.0.0
1237
- */
1238
- stopAutoSave(): this;
1239
-
1240
- /**
1241
- * The isAutoSaving method lets you find out if the Persister is currently
1242
- * automatically saving its content.
1243
- * @returns A boolean indicating whether the Persister is currently
1244
- * autoSaving.
1245
- * @example
1246
- * This example creates a Persister and queries whether it is autoSaving.
1247
- *
1248
- * ```js
1249
- * import {createStore} from 'tinybase';
1250
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1251
- *
1252
- * const persister = createSessionPersister(createStore(), 'pets');
1253
- *
1254
- * console.log(persister.isAutoSaving());
1255
- * // -> false
1256
- *
1257
- * await persister.startAutoSave();
1258
- * console.log(persister.isAutoSaving());
1259
- * // -> true
1260
- *
1261
- * await persister.stopAutoSave();
1262
- * console.log(persister.isAutoSaving());
1263
- * // -> false
1264
- * ```
1265
- * @category Save
1266
- * @since v5.0.0
1267
- */
1268
- isAutoSaving(): boolean;
1269
-
1270
- /**
1271
- * The getStatus method lets you find out if the Persister is currently in the
1272
- * process of loading or saving content.
1273
- *
1274
- * It can only be doing one or the other (or neither) at any given time. The
1275
- * Status enum is returned, where 0 means idle, 1 means loading, and 2 means
1276
- * saving.
1277
- *
1278
- * This method is only likely to be useful for Persister implementations that
1279
- * have asynchronous load or save operations. The status for synchronous
1280
- * persister media (such as browser local or session storage) will switch back
1281
- * to idle before you are able to query it.
1282
- * @returns A value of type Status indicating whether the Persister is idle,
1283
- * loading, or saving.
1284
- * @example
1285
- * This example creates a Persister and queries its status.
1286
- *
1287
- * ```js
1288
- * import {createStore} from 'tinybase';
1289
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1290
- *
1291
- * const persister = createSessionPersister(createStore(), 'pets');
1292
- *
1293
- * console.log(persister.getStatus());
1294
- * // -> 0
1295
- * ```
1296
- * @category Lifecycle
1297
- * @since v5.3.0
1298
- */
1299
- getStatus(): Status;
1300
-
1301
- /**
1302
- * The addStatusListener method registers a listener function with the
1303
- * Persister that will be called whenever it starts or stops loading or
1304
- * saving.
1305
- *
1306
- * The provided listener is a StatusListener function, and will be called with
1307
- * a reference to the Persister and the new Status: 0 means now idle, 1 means
1308
- * now loading, and 2 means now saving.
1309
- * @param listener The function that will be called whenever the Persister
1310
- * starts or stops loading or saving.
1311
- * @returns A unique Id for the listener that can later be used to remove it.
1312
- * @example
1313
- * This example registers a listener that responds to changes in the state of
1314
- * the Persister.
1315
- *
1316
- * ```js
1317
- * import {createStore} from 'tinybase';
1318
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1319
- *
1320
- * const persister = createSessionPersister(createStore(), 'pets');
1321
- *
1322
- * const listenerId = persister.addStatusListener((persister, status) => {
1323
- * console.log(
1324
- * `${persister.getStorageName()} persister status changed to ${status}`,
1325
- * );
1326
- * });
1327
- *
1328
- * await persister.load();
1329
- * // -> 'pets persister status changed to 1'
1330
- * // -> 'pets persister status changed to 0'
1331
- * await persister.save();
1332
- * // -> 'pets persister status changed to 2'
1333
- * // -> 'pets persister status changed to 0'
1334
- *
1335
- * persister.delListener(listenerId);
1336
- * ```
1337
- * @category Listener
1338
- * @since v5.3.0
1339
- */
1340
- addStatusListener(listener: StatusListener<Persist>): Id;
1341
-
1342
- /**
1343
- * The delListener method removes a listener that was previously added to the
1344
- * Persister.
1345
- *
1346
- * Use the Id returned by whichever method was used to add the listener. Note
1347
- * that the Persister may re-use this Id for future listeners added to it.
1348
- * @param listenerId The Id of the listener to remove.
1349
- * @returns A reference to the Persister.
1350
- * @example
1351
- * This example registers a listener and then removes it.
1352
- *
1353
- * ```js
1354
- * import {createStore} from 'tinybase';
1355
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1356
- *
1357
- * const persister = createSessionPersister(createStore(), 'pets');
1358
- *
1359
- * const listenerId = persister.addStatusListener((_persister, status) => {
1360
- * console.log(`Status changed to ${status}`);
1361
- * });
1362
- *
1363
- * await persister.load();
1364
- * // -> `Status changed to 1`
1365
- * // -> `Status changed to 0`
1366
- *
1367
- * persister.delListener(listenerId);
1368
- *
1369
- * await persister.load();
1370
- * // -> undefined
1371
- * // The listener is not called.
1372
- * ```
1373
- * @category Listener
1374
- * @since v5.3.0
1375
- */
1376
- delListener(listenerId: Id): this;
1377
-
1378
- /**
1379
- * The schedule method allows you to queue up a series of asynchronous actions
1380
- * that must run in sequence during persistence.
1381
- *
1382
- * For example, a database Persister may need to ensure that multiple
1383
- * asynchronous tasks to check and update the database schema are completed
1384
- * before data is written to it. Therefore it's most likely you will be using
1385
- * this method inside your `setPersisted` implementation.
1386
- *
1387
- * Call this method to add a single asynchronous action, or a sequence of them
1388
- * in one call. This will also start to run the first task in the queue (which
1389
- * once complete will then run the next, and so on), and so this method itself
1390
- * is also asynchronous and returns a promise of the Persister.
1391
- * @param actions One or many functions which will be scheduled, and which can
1392
- * be asynchronous.
1393
- * @returns A reference to the Persister object.
1394
- * @example
1395
- * This example creates a custom Persister object against a newly-created
1396
- * Store and then sequences two tasks in order to update its data on a
1397
- * hypothetical remote system.
1398
- *
1399
- * ```js yolo
1400
- * import {
1401
- * checkRemoteSystemIsReady,
1402
- * getDataFromRemoteSystem,
1403
- * sendDataToRemoteSystem,
1404
- * } from 'custom-remote-handlers';
1405
- * import {createStore} from 'tinybase';
1406
- * import {createCustomPersister} from 'tinybase/persisters';
1407
- *
1408
- * const store = createStore();
1409
- * const persister = createCustomPersister(
1410
- * store,
1411
- * async () => {
1412
- * // getPersisted
1413
- * return await getDataFromRemoteSystem();
1414
- * },
1415
- * async (getContent) => {
1416
- * // setPersisted
1417
- * await persister.schedule(
1418
- * async () => await checkRemoteSystemIsReady(),
1419
- * async () => await sendDataToRemoteSystem(getContent()),
1420
- * );
1421
- * },
1422
- * (listener) => setInterval(listener, 1000),
1423
- * (interval) => clearInterval(interval),
1424
- * );
1425
- * ```
1426
- * @category Lifecycle
1427
- * @since v4.0.0
1428
- */
1429
- schedule(...actions: (() => Promise<any>)[]): Promise<this>;
1430
-
1431
- /**
1432
- * The getStore method returns a reference to the underlying Store or
1433
- * MergeableStore that is backing this Persister object.
1434
- * @returns A reference to the Store or MergeableStore.
1435
- * @example
1436
- * This example creates a Persister object against a newly-created Store and
1437
- * then gets its reference in order to update its data.
1438
- *
1439
- * ```js
1440
- * import {createStore} from 'tinybase';
1441
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1442
- *
1443
- * const persister = createSessionPersister(createStore(), 'pets');
1444
- * await persister.startAutoSave();
1445
- *
1446
- * persister.getStore().setTables({pets: {fido: {species: 'dog'}}});
1447
- * // ...
1448
- * console.log(sessionStorage.getItem('pets'));
1449
- * // -> '[{"pets":{"fido":{"species":"dog"}}},{}]'
1450
- *
1451
- * sessionStorage.clear();
1452
- * ```
1453
- * @category Getter
1454
- * @since v1.0.0
1455
- */
1456
- getStore(): PersistedStore<Persist>;
1457
-
1458
- /**
1459
- * The destroy method should be called when this Persister object is no longer
1460
- * used.
1461
- *
1462
- * This guarantees that all of the listeners that the object registered with
1463
- * the underlying Store and storage are removed and it can be correctly
1464
- * garbage collected. It is equivalent to running the stopAutoLoad method and
1465
- * the stopAutoSave method in succession.
1466
- * @returns A reference to the Persister object.
1467
- * @example
1468
- * This example creates a Store, associates a Persister object with it (that
1469
- * registers a TablesListener with the underlying Store), and then destroys it
1470
- * again, removing the listener.
1471
- *
1472
- * ```js
1473
- * import {createStore} from 'tinybase';
1474
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1475
- *
1476
- * const store = createStore();
1477
- * const persister = createSessionPersister(store, 'pets');
1478
- * await persister.startAutoSave();
1479
- *
1480
- * console.log(store.getListenerStats().transaction);
1481
- * // -> 1
1482
- *
1483
- * persister.destroy();
1484
- *
1485
- * console.log(store.getListenerStats().transaction);
1486
- * // -> 0
1487
- * ```
1488
- * @category Lifecycle
1489
- * @since v1.0.0
1490
- */
1491
- destroy(): this;
1492
-
1493
- /**
1494
- * The getStats method provides a set of statistics about the Persister, and
1495
- * is used for debugging purposes.
1496
- *
1497
- * The PersisterStats object contains a count of the number of times the
1498
- * Persister has loaded and saved data.
1499
- *
1500
- * The method is intended to be used during development to ensure your
1501
- * persistence layer is acting as expected, for example.
1502
- * @returns A PersisterStats object containing Persister load and save
1503
- * statistics.
1504
- * @example
1505
- * This example gets the load and save statistics of a Persister object.
1506
- * Remember that the startAutoLoad method invokes an explicit load when it
1507
- * starts, and the startAutoSave method invokes an explicit save when it
1508
- * starts - so those numbers are included in addition to the loads and saves
1509
- * invoked by changes to the Store and to the underlying storage.
1510
- *
1511
- * ```js
1512
- * import {createStore} from 'tinybase';
1513
- * import {createSessionPersister} from 'tinybase/persisters/persister-browser';
1514
- *
1515
- * const store = createStore();
1516
- * const persister = createSessionPersister(store, 'pets');
1517
- *
1518
- * await persister.startAutoLoad({pets: {fido: {species: 'dog'}}});
1519
- * await persister.startAutoSave();
1520
- *
1521
- * store.setTables({pets: {felix: {species: 'cat'}}});
1522
- * // ...
1523
- *
1524
- * sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
1525
- * // -> StorageEvent('storage', {storageArea: sessionStorage, key: 'pets'})
1526
- * // ...
1527
- *
1528
- * console.log(persister.getStats());
1529
- * // -> {loads: 2, saves: 2}
1530
- *
1531
- * persister.destroy();
1532
- * sessionStorage.clear();
1533
- * ```
1534
- * @category Development
1535
- * @since v1.0.0
1536
- */
1537
- getStats(): PersisterStats;
1538
- //
1539
- }
1540
-
1541
- /**
1542
- * The AnyPersister type is a convenient alias for any type of Persister that
1543
- * can persist Store or MergeableStore objects.
1544
- * @category Mergeable
1545
- * @since v5.3.0
1546
- */
1547
- export type AnyPersister = Persister<Persists>;
1548
-
1549
- /**
1550
- * The DatabaseExecuteCommand type describes a function that is used to execute
1551
- * commands against a database.
1552
- *
1553
- * This is only used when developing custom database-oriented Persisters, and
1554
- * most TinyBase users will not need to be particularly aware of it.
1555
- *
1556
- * It is modelled around the common pattern of database SDKs being able to
1557
- * execute commands with parameters, and have those (probably asynchronous)
1558
- * command executions return an array of objects, where each object represents a
1559
- * row.
1560
- * @param sql The SQL string to execute, which may include positional parameter
1561
- * placeholders.
1562
- * @param params An array of parameters to pass to the SQL command.
1563
- * @returns An promise of an array of objects, where each object represents a
1564
- * database result row (if the command was a query).
1565
- * @category Creation
1566
- * @since v5.2.0
1567
- */
1568
- export type DatabaseExecuteCommand = (
1569
- sql: string,
1570
- params?: any[],
1571
- ) => Promise<{[field: string]: any}[]>;
1572
-
1573
- /**
1574
- * The DatabaseChangeListener type describes a function that is used to listen
1575
- * for changes to the data in a database.
1576
- *
1577
- * This is only used when developing custom database-oriented Persisters, and
1578
- * most TinyBase users will not need to be particularly aware of it.
1579
- *
1580
- * This function should be called with the name of a relevant table that has
1581
- * changed, possible through the use of events, triggers, or notifications,
1582
- * dependent on the specific database implementation.
1583
- * @param tableName The name of the table that has changed.
1584
- * @category Creation
1585
- * @since v5.2.0
1586
- */
1587
- export type DatabaseChangeListener = (tableName: string) => void;
1588
-
1589
- /**
1590
- * The createCustomPersister function creates a Persister object that you can
1591
- * configure to persist the Store in any way you wish.
1592
- *
1593
- * This is only used when developing custom Persisters, and most TinyBase users
1594
- * will not need to be particularly aware of it.
1595
- *
1596
- * As well as providing a reference to the Store to persist, you must provide
1597
- * functions that handle how to fetch, write, and listen to, the persistence
1598
- * layer.
1599
- *
1600
- * The other creation functions (such as the createSessionPersister function and
1601
- * createFilePersister function, for example) all use this function under the
1602
- * covers. See those implementations for ideas on how to implement your own
1603
- * Persister types.
1604
- *
1605
- * This API changed in v4.0. Any custom persisters created on previous versions
1606
- * should be upgraded. Most notably, the `setPersisted` function parameter is
1607
- * provided with a `getContent` function to get the content from the Store
1608
- * itself, rather than being passed pre-serialized JSON. It also receives
1609
- * information about the changes made during a transaction. The `getPersisted`
1610
- * function must return the content (or nothing) rather than JSON.
1611
- * `startListeningToPersisted` has been renamed `addPersisterListener`, and
1612
- * `stopListeningToPersisted` has been renamed `delPersisterListener`.
1613
- * @param store The Store to persist.
1614
- * @param getPersisted An asynchronous function which will fetch content from
1615
- * the persistence layer (or `undefined` if not present).
1616
- * @param setPersisted An asynchronous function which will send content to the
1617
- * persistence layer. Since v4.0, it receives functions for getting the Store
1618
- * content and information about the changes made during a transaction. Since
1619
- * v5.0, the changes are received directly by reference, rather than an
1620
- * accessor.
1621
- * @param addPersisterListener A function that will register a `listener`
1622
- * listener on underlying changes to the persistence layer. You can return a
1623
- * listening handle that will be provided again when `delPersisterListener` is
1624
- * called. This function can be asynchronous.
1625
- * @param delPersisterListener A function that will unregister the listener from
1626
- * the underlying changes to the persistence layer. It receives whatever was
1627
- * returned from your `addPersisterListener` implementation.
1628
- * @param onIgnoredError An optional handler for the errors that the Persister
1629
- * would otherwise ignore when trying to save or load data. This is suitable for
1630
- * debugging persistence issues in a development environment, since v4.0.4.
1631
- * @param persist Since v5.0, an optional integer from the Persists enum to
1632
- * indicate which types of Store are supported by this Persister: `1` indicates
1633
- * only a regular Store is supported, `2` indicates only a MergeableStore is
1634
- * supported, and `3` indicates that both Store and MergeableStore are
1635
- * supported.
1636
- * @returns A reference to the new Persister object.
1637
- * @example
1638
- * This example creates a custom Persister object and persists a Store to a
1639
- * local string called `persistedJson` and which would automatically load by
1640
- * polling for changes every second. It implicitly supports only a regular
1641
- * Store.
1642
- *
1643
- * ```js
1644
- * import {createStore} from 'tinybase';
1645
- * import {createCustomPersister} from 'tinybase/persisters';
1646
- *
1647
- * const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
1648
- * let persistedJson;
1649
- *
1650
- * const persister = createCustomPersister(
1651
- * store,
1652
- * async () => {
1653
- * // getPersisted
1654
- * return JSON.parse(persistedJson);
1655
- * },
1656
- * async (getContent) => {
1657
- * // setPersisted
1658
- * persistedJson = JSON.stringify(getContent());
1659
- * },
1660
- * (listener) => setInterval(listener, 1000),
1661
- * (interval) => clearInterval(interval),
1662
- * );
1663
- *
1664
- * await persister.save();
1665
- * console.log(persistedJson);
1666
- * // -> '[{"pets":{"fido":{"species":"dog"}}},{}]'
1667
- *
1668
- * persistedJson = '[{"pets":{"fido":{"species":"dog","color":"brown"}}},{}]';
1669
- * await persister.load();
1670
- *
1671
- * console.log(store.getTables());
1672
- * // -> {pets: {fido: {species: 'dog', color: 'brown'}}}
1673
- *
1674
- * persister.destroy();
1675
- * ```
1676
- * @example
1677
- * This example demonstrates a Persister creation function which returns a
1678
- * Persister. This can persists a store to a local string called `persistedJson`
1679
- * and which would automatically load by polling for changes every second.
1680
- * It emits warnings to the console and explicitly supports either a Store or a
1681
- * MergeableStore.
1682
- *
1683
- * ```js
1684
- * import {createMergeableStore, createStore} from 'tinybase';
1685
- * import {Persists, createCustomPersister} from 'tinybase/persisters';
1686
- *
1687
- * let persistedJson;
1688
- * const createJsonPersister = (storeOrMergeableStore) =>
1689
- * createCustomPersister(
1690
- * storeOrMergeableStore,
1691
- * async () => {
1692
- * // getPersisted
1693
- * return JSON.parse(persistedJson);
1694
- * },
1695
- * async (getContent) => {
1696
- * // setPersisted
1697
- * persistedJson = JSON.stringify(getContent());
1698
- * },
1699
- * (listener) => setInterval(listener, 1000),
1700
- * (interval) => clearInterval(interval),
1701
- * console.warn,
1702
- * Persists.StoreOrMergeableStore,
1703
- * );
1704
- *
1705
- * const store = createStore();
1706
- * store.setTables({pets: {fido: {species: 'dog'}}});
1707
- * const storePersister = createJsonPersister(store);
1708
- * await storePersister.save();
1709
- * console.log(persistedJson);
1710
- * // -> '[{"pets":{"fido":{"species":"dog"}}},{}]'
1711
- * storePersister.destroy();
1712
- *
1713
- * const mergeableStore = createMergeableStore('mergeableStore1'); // !resetHlc
1714
- * mergeableStore.setTables({pets: {fido: {species: 'dog'}}});
1715
- * const mergeableStorePersister = createJsonPersister(mergeableStore);
1716
- * await mergeableStorePersister.save();
1717
- * console.log(JSON.parse(persistedJson));
1718
- * // ->
1719
- * [
1720
- * [
1721
- * {
1722
- * pets: [
1723
- * {
1724
- * fido: [
1725
- * {species: ['dog', 'Nn1JUF-----Zjl0M', 4176151067]},
1726
- * '',
1727
- * 2722999044,
1728
- * ],
1729
- * },
1730
- * '',
1731
- * 3367164653,
1732
- * ],
1733
- * },
1734
- * '',
1735
- * 30627183,
1736
- * ],
1737
- * [{}, '', 0],
1738
- * ];
1739
- * mergeableStorePersister.destroy();
1740
- * ```
1741
- * @category Creation
1742
- * @since v1.0.0
1743
- */
1744
- export function createCustomPersister<
1745
- ListenerHandle,
1746
- Persist extends Persists = Persists.StoreOnly,
1747
- >(
1748
- store: PersistedStore<Persist>,
1749
- getPersisted: () => Promise<PersistedContent<Persist> | undefined>,
1750
- setPersisted: (
1751
- getContent: () => PersistedContent<Persist>,
1752
- changes?: PersistedChanges<Persist>,
1753
- ) => Promise<void>,
1754
- addPersisterListener: (
1755
- listener: PersisterListener<Persist>,
1756
- ) => ListenerHandle | Promise<ListenerHandle>,
1757
- delPersisterListener: (listenerHandle: ListenerHandle) => void,
1758
- onIgnoredError?: (error: any) => void,
1759
- persist?: Persist,
1760
- ): Persister<Persist>;
1761
-
1762
- /**
1763
- * The createCustomSqlitePersister function creates a Persister object that you
1764
- * can configure to persist the Store to a SQLite database.
1765
- *
1766
- * This is only used when developing custom database-oriented Persisters, and
1767
- * most TinyBase users will not need to be particularly aware of it.
1768
- *
1769
- * All of the TinyBase SQLite-oriented Persister functions use this function
1770
- * under the covers, and so you may wish to look at those implementations for
1771
- * ideas on how to build your own Persister type, and as functional examples.
1772
- * Examine the implementation of the createSqlite3Persister function as a good
1773
- * starting point, for example.
1774
- * @param store The Store to persist.
1775
- * @param configOrStoreTableName A DatabasePersisterConfig object, or a string
1776
- * that will be used as the name of the Store's table in the database.
1777
- * @param executeCommand A function that will execute a command against the
1778
- * database.
1779
- * @param addChangeListener A function that will register a listener for changes
1780
- * to the database.
1781
- * @param delChangeListener A function that will unregister the listener for
1782
- * changes to the database.
1783
- * @param onSqlCommand A function that will be called for each SQL command
1784
- * executed against the database.
1785
- * @param onIgnoredError An optional handler for the errors that the Persister
1786
- * would otherwise ignore when trying to save or load data. This is suitable for
1787
- * debugging persistence issues in a development environment.
1788
- * @param destroy A function that will be called to perform any extra clean up
1789
- * on the Persister.
1790
- * @param persist An integer from the Persists enum to indicate which types of
1791
- * Store are supported by this Persister: `1` indicates only a regular Store is
1792
- * supported, `2` indicates only a MergeableStore is supported, and `3`
1793
- * indicates that both Store and MergeableStore are supported.
1794
- * @param thing A reference to the database or connection that can be returned
1795
- * with a method, by default called `getDb`.
1796
- * @param getThing An optional string that will be used to get the reference to
1797
- * the database or connection from the Persister, defaulting to `getDb`.
1798
- * @returns A reference to the new SQLite-oriented Persister object.
1799
- * @category Creation
1800
- * @since v5.2.0
1801
- */
1802
- export function createCustomSqlitePersister<
1803
- ListenerHandle,
1804
- Persist extends Persists = Persists.StoreOnly,
1805
- >(
1806
- store: PersistedStore<Persist>,
1807
- configOrStoreTableName: DatabasePersisterConfig | string | undefined,
1808
- executeCommand: DatabaseExecuteCommand,
1809
- addChangeListener: (listener: DatabaseChangeListener) => ListenerHandle,
1810
- delChangeListener: (listenerHandle: ListenerHandle) => void,
1811
- onSqlCommand: ((sql: string, params?: any[]) => void) | undefined,
1812
- onIgnoredError: ((error: any) => void) | undefined,
1813
- destroy: () => void,
1814
- persist: Persist,
1815
- thing: any,
1816
- getThing?: string,
1817
- ): Persister<Persist>;
1818
-
1819
- /**
1820
- * The createCustomSqlitePersister function creates a Persister object that you
1821
- * can configure to persist the Store to a PostgreSQL database.
1822
- *
1823
- * This is only used when developing custom database-oriented Persisters, and
1824
- * most TinyBase users will not need to be particularly aware of it.
1825
- *
1826
- * All of the TinyBase PostgreSQL-oriented Persister functions use this function
1827
- * under the covers, and so you may wish to look at those implementations for
1828
- * ideas on how to build your own Persister type, and as functional
1829
- * examples. Examine the implementation of the createPostgresPersister function
1830
- * as a good starting point, for example.
1831
- * @param store The Store to persist.
1832
- * @param configOrStoreTableName A DatabasePersisterConfig object, or a string
1833
- * that will be used as the name of the Store's table in the database.
1834
- * @param executeCommand A function that will execute a command against the
1835
- * database.
1836
- * @param addChangeListener A function that will register a listener for changes
1837
- * to the database.
1838
- * @param delChangeListener A function that will unregister the listener for
1839
- * changes to the database.
1840
- * @param onSqlCommand A function that will be called for each SQL command
1841
- * executed against the database.
1842
- * @param onIgnoredError An optional handler for the errors that the Persister
1843
- * would otherwise ignore when trying to save or load data. This is suitable for
1844
- * debugging persistence issues in a development environment.
1845
- * @param destroy A function that will be called to perform any extra clean up
1846
- * on the Persister.
1847
- * @param persist An integer from the Persists enum to indicate which types of
1848
- * Store are supported by this Persister: `1` indicates only a regular Store is
1849
- * supported, `2` indicates only a MergeableStore is supported, and `3`
1850
- * indicates that both Store and MergeableStore are supported.
1851
- * @param thing A reference to the database or connection that can be returned
1852
- * with a method, by default called `getDb`.
1853
- * @param getThing An optional string that will be used to get the reference to
1854
- * the database or connection from the Persister, defaulting to `getDb`.
1855
- * @returns A reference to the new Persister object.
1856
- * @category Creation
1857
- * @since v5.2.0
1858
- */
1859
- export function createCustomPostgreSqlPersister<
1860
- ListenerHandle,
1861
- Persist extends Persists = Persists.StoreOnly,
1862
- >(
1863
- store: PersistedStore<Persist>,
1864
- configOrStoreTableName: DatabasePersisterConfig | string | undefined,
1865
- executeCommand: DatabaseExecuteCommand,
1866
- addChangeListener: (
1867
- channel: string,
1868
- listener: DatabaseChangeListener,
1869
- ) => Promise<ListenerHandle>,
1870
- delChangeListener: (listenerHandle: ListenerHandle) => void,
1871
- onSqlCommand: ((sql: string, params?: any[]) => void) | undefined,
1872
- onIgnoredError: ((error: any) => void) | undefined,
1873
- destroy: () => void,
1874
- persist: Persist,
1875
- thing: any,
1876
- getThing?: string,
1877
- ): Persister<Persist>;