(
definition: EntityDefinition<Data, View>,
{ db, cleanup }: EntityClientConfig
)
| 51 | * It also initializes synchronization and persistance. |
| 52 | */ |
| 53 | export function createEntityClient<Data, View>( |
| 54 | definition: EntityDefinition<Data, View>, |
| 55 | { db, cleanup }: EntityClientConfig |
| 56 | ): EntityClient<Data, View> { |
| 57 | const store = createEntityStore<Data, View>(definition, db, cleanup); |
| 58 | |
| 59 | // Allow listening to CRUD updates in the store |
| 60 | const events = createEventsEmmiter<EntityStoreEvents<Data, View>>( |
| 61 | definition.config.name |
| 62 | ); |
| 63 | |
| 64 | const { created, removed, updated } = definition.config.events ?? {}; |
| 65 | |
| 66 | if (created) { |
| 67 | cleanup.next = events.on("created", created); |
| 68 | } |
| 69 | |
| 70 | if (removed) { |
| 71 | cleanup.next = events.on("removed", removed); |
| 72 | } |
| 73 | |
| 74 | if (updated) { |
| 75 | cleanup.next = events.on("updated", updated); |
| 76 | } |
| 77 | |
| 78 | cleanup.next = events.onOneOf(["created", "removed", "updated"], (change) => { |
| 79 | const currentTransaction = getCurrentTransaction(); |
| 80 | |
| 81 | if (!db.events.hasListeners("transaction")) { |
| 82 | if (currentTransaction) { |
| 83 | console.warn( |
| 84 | "running runTransaction with operations on db that is not listening to transactions." |
| 85 | ); |
| 86 | } |
| 87 | return; |
| 88 | } |
| 89 | |
| 90 | if (!currentTransaction) { |
| 91 | // Emit change as one-step transaction |
| 92 | const transaction = createTransactionWithChanges([ |
| 93 | change as EntityChangeEvent<unknown, unknown>, |
| 94 | ]); |
| 95 | |
| 96 | db.events.emit("transaction", { type: "transaction", transaction }); |
| 97 | return; |
| 98 | } |
| 99 | |
| 100 | currentTransaction.pushChange( |
| 101 | change as EntityChangeEvent<unknown, unknown> |
| 102 | ); |
| 103 | }); |
| 104 | |
| 105 | cleanup.next = events.removeAllListeners; |
| 106 | |
| 107 | const { query, findById, sort, find, findFirst } = store; |
| 108 | |
| 109 | function createStoreEntity(input: Partial<Data>) { |
| 110 | return createEntity<Data, View>({ data: input, client }); |
no test coverage detected