fix(sync): block patches before initial hydration (#21)

This commit is contained in:
richard 2024-09-20 15:32:20 -07:00 • committed by GitHub
parent f0acadb4e6
commit 9ba552cb6c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 37 additions and 16 deletions

5
src/index.d.ts vendored
View file

@ -290,6 +290,11 @@ declare namespace Charm {
* The atoms to synchronize with the server.
*/
atoms: Atoms;
/**
* Whether to ignore patches sent before the client has been hydrated.
* Defaults to `true`.
*/
ignoreUnhydrated?: boolean;
}
interface ServerOptions<Molecules extends MoleculeMap> {

View file

@ -9,6 +9,11 @@ type ClientOptions = {
The atoms to synchronize with the server.
]=]
atoms: { [string]: Atom<any> },
--[=[
Whether to ignore patches sent before the client has been hydrated.
Default is `true`.
]=]
ignoreUnhydrated: boolean?,
}
type ClientSyncer = {
@ -30,12 +35,22 @@ type ClientSyncer = {
]=]
local function client(options: ClientOptions): ClientSyncer
local atoms = options.atoms
local ignoreUnhydrated = options.ignoreUnhydrated ~= false
local self = {} :: ClientSyncer
local hydrated = false
-- Apply the state changes sent by the server.
function self:sync(...)
for index = 1, select("#", ...) do
local payload = select(index, ...)
local payload: SyncPayload = select(index, ...)
if ignoreUnhydrated and payload.type == "patch" and not hydrated then
-- If the client is not initialized, ignore patches. This is
-- to prevent patching incomplete state.
continue
end
hydrated = true
store.batch(function()
for key, state in next, payload.data do