Skip to content

Commit

Permalink
Remove $register and call $sync manually
Browse files Browse the repository at this point in the history
Require users to call the initial sync function themselves.
Remove the $register function, and move the method registrations into
the Model constructor.

Update the docs
  • Loading branch information
zknill committed Oct 20, 2023
1 parent ba27278 commit 0a57853
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 170 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ const model = await modelsClient.models.get<Post>({
$merge: merge,
})

// run the initial sync
await model.$sync()

// subscribe to live changes to the model data!
model.subscribe((err, post) => {
if (err) {
Expand Down
11 changes: 7 additions & 4 deletions docs/concepts/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,16 @@ Note that we pass in the shape of our data model (`Post`) as a type parameter.
In order to instantiate the model, we need to pass some *registrations* which link up the model to your application code.

```ts
await modelsClient.models.get<Post>({
const model = await modelsClient.models.get<Post>({
name: /* ... */,
channelName: /* ... */,
$sync: /* ... */,
$merge: /* ... */,
})
```

Let's take a look at each of these registrations in turn.
// run the initial sync
await model.$sync()
```

## Sync Function

Expand All @@ -57,10 +58,12 @@ async function sync() {
return result.json();
}

await modelsClient.models.get<Post>({
const model = await modelsClient.models.get<Post>({
$sync: /* ... */,
/* other registrations */
})

await model.$sync()
```

The model will invoke this function at the start of its lifecycle to initialise your model state. Additionally, this function will be invoked if the model needs to re-synchronise at any point, for example after an extended period of network disconnectivity.
Expand Down
5 changes: 3 additions & 2 deletions src/Model.discontinuity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,12 @@ describe('Model', () => {
let counter = 0;

const sync = vi.fn(async () => `${counter++}`);
const model = new Model<string>('test', { ably, channelName, logger });
const mergeFn = vi.fn(async (_, event) => {
return event.data;
});
await model.$register({ $sync: sync, $merge: mergeFn });

const model = new Model<string>('test', { $sync: sync, $merge: mergeFn }, { ably, channelName, logger });
await model.$sync();

expect(sync).toHaveBeenCalledOnce();

Expand Down
Loading

0 comments on commit 0a57853

Please sign in to comment.