Reads never wait
list() and get() read the local replica. No spinner, no network, the same answer on a train in a tunnel.
Tools · Use an API · v0.2.0
restep-syncWorks offlineA local replica of your collections, kept up to date incrementally with the sync profile. Writes show at once, queue while offline and reach the server exactly once.
Browser or Node 18+ · npm install restep-sync
list() and get() read the local replica. No spinner, no network, the same answer on a train in a tunnel.
Each create gets its Idempotency-Key when it is queued, and keeps it after a restart. A lost response is retried, not duplicated. Where it cannot be sure, it stops and asks you.
For a collection that declares sync, it asks :changes since its last state and fetches just those items. A full download happens once, or when the server forgets the state.
Every update and delete carries If-Match. When someone got there first, the server wins, the client wins, or your function merges the two.
Per collection it keeps the copy the server confirmed (each item with its ETag) and the state of the sync profile. Your writes go into a first-in, first-out queue. What list() and get() return is the confirmed copy with the queue applied on top, so undoing an optimistic change is just removing its operation from the queue.
rel="service-desc" that leads to one. A restep that does not follow the grammar of 1.1, or is of another major version, is not Restep 1, and it does not open. With no discovery document it assumes core only, with each collection at /<name>. It checks that each collection exists and is not a subcollection. A collection is synced with :changes only if it declares sync, the API announces the profile and declares "restep": "1.0-draft.6": sync is experimental (1.2), and that is the only text of it this client implements. Then it also needs filter on id with in. The rest are reloaded in full; db.mode(name) says which. Offline, it uses the discovery document it saved last time. Opening downloads no items: the first sync() does.GET /books?limit=<max_limit>, following next until null, and keeping the state of the first page.GET /books:changes?since=<state>. Created and updated ids are fetched with filter[id][in]=…, a page at a time; destroyed ones are removed, and so is an id that does not come back (it can no longer be seen). With has_more: true it asks again. The new state is saved only after the changes are applied. A 410 state_expired, or an invalid_parameter on since, reloads the collection and keeps your queued writes.create is a POST with its stored Idempotency-Key, sent only if the API announces writes, and not without credentials where idempotency.anonymous is false (7.1); the provisional local-… id becomes the server’s, in the replica and in the rest of the queue. Where the collection’s id_from is "client", the client picks the id (a UUID v4) and there is no provisional one; with "client" or "either", create() also takes an id in the body (5.1). If such a create is retried after a lost response and gets 409 with taken at /id, it reads the item and, if it is there, counts it as created. update is a PATCH with application/merge-patch+json and If-Match; delete, a DELETE with If-Match, where a 404 counts as done.408, 425, 429 and 5xx wait with exponential backoff, and never before the server’s Retry-After. So does a 409 request_in_progress, the same request still running (7.1), with the same key. A create that is not safe to repeat (5.7: no writes, or no key can be sent, and the server picks the id) becomes uncertain after a lost response or a 408, 500, 502 or 504: you get an error, the report carries uncertain with its opId, and the queue waits until you call sync({ retryUncertain: true }), which may duplicate it, or discard(opId). 429 and 503 only ever reach requests that had no effect, so those are retried. Any other 4xx, 409 conflict included, is permanent: the operation (and those that depend on it) leaves the queue, the local change is undone and you get an error event with the problem+json.The If-Match of an update or delete is the _etag the item brought in the listing (7.2), so it does not read the item first. Only if the listing carries no _etag (a server that leaves it out) does it read the item before writing: if it is still the version you saw, it uses that ETag; if not, it is a conflict, and nothing was written. _etag is not part of the data list() and get() return.
The token and the headers go only to the API’s origin, and a next or Location with a scheme other than https or the root’s is not followed (3).
A collection without sync, or an API that declares another version, still works: every sync reloads that collection in full. Dearer, but correct.
One ES module, no dependencies. Node 18 or later, or any modern browser. In a browser without a bundler, import it from https://cdn.jsdelivr.net/npm/restep-sync@0.2/restep-sync.mjs.
npm install restep-sync
import { openRestepSync, fileStorage } from 'restep-sync';
const db = await openRestepSync({
url: 'https://api.example.com/',
collections: ['books'],
storage: fileStorage('./replica.json'), // memoryStorage() by default; indexedDBStorage() in a browser
});
await db.sync(); // opening does not download: this does
To be incremental it needs collections that declare sync, under 1.0-draft.6. For its retries and If-Match to mean anything it needs writes. Without writes it sends no Idempotency-Key, so a create without an id of its own can become uncertain, and it still sends If-Match, but the server owes it nothing (7.1).
These ran against a copy of the reference server with the sync profile added, on port 18860, with the El Marcapáginas bookshop data.
const db = await openRestepSync({ url: 'http://localhost:18860/', collections: ['books'],
storage: fileStorage('./replica.json') });
db.on('change', (e) => console.log('change', e.source, e.collection, e.created, e.updated, e.destroyed));
db.list('books').length; // 0: nothing downloaded yet
console.log(await db.sync());
console.log(db.list('books', { filter: { category: 'novela-negra' }, sort: '-price' })
.map((b) => `${b.id} ${b.price} ${b.title}`));
$ node first.mjs
change remote books [ '12', '15', '21', '23', '30', '50', '7' ] [] []
{ online: true, pushed: 0, dropped: 0, conflicts: 0, pending: 0,
pulled: { books: { created: 7, updated: 0, destroyed: 0 } }, reset: [], errors: [] }
[ '7 18.50 La niebla de Portugalete',
'12 16.90 El último ferry',
'15 14.95 Lluvia sobre Deusto' ]
The new book shows at once with a provisional id. With autoPush (the default) the queue goes out right away; when the server answers, the push event says which id replaced which.
const nuevo = await db.create('books', { title: 'Faro apagado', price: '9.90', category: 'poesia' });
await db.update('books', '7', { price: '15.00' });
await db.sync();
console.log(db.resolveId('books', nuevo.id));
change local books [ 'local-ba68133e-f298-48bd-a221-46babd9dd6f5' ] [] []
change local books [] [ '7' ] []
change push books [ '100' ] [] [] replaced: { 'local-ba68133e-…': '100' }
change push books [] [ '7' ] []
change remote books [] [ '100', '7' ] []
100
The old id keeps working: db.get('books', nuevo.id) returns book 100.
With the server down, the change stays in the queue and in the file. The report says online: false instead of throwing.
await db.update('books', '30', { price: '13.00' });
console.log(await db.sync());
db.get('books', '30').price; // '13.00', already
{ online: false, pushed: 0, dropped: 0, conflicts: 0, pending: 1, pulled: {}, reset: [], errors: [] }
Close the program, start the server again, open the same file and sync. The server restarted, so the old state is unknown to it: it answers 410 and the collection reloads, after the queue has gone out.
{ online: true, pushed: 1, dropped: 0, conflicts: 0, pending: 0,
pulled: { books: { created: 0, updated: 1, destroyed: 1 } }, reset: [ 'books' ], errors: [] }
Someone renames book 12 on the server while you change its price from a stale copy. Your function sees the three versions and decides:
db.on('conflict', (e) => console.log('conflict', e.id, e.resolution));
await db.update('books', '12', { price: '17.50' }, {
onConflict: ({ base, server, local, patch }) => {
console.log({ base: base.title, server: server.title, local: [local.title, local.price], patch });
return 'client'; // resend my patch on top of their version
},
});
await db.sync();
console.log(db.get('books', '12'));
{ base: 'El último ferry', server: 'El último ferry (2.ª ed.)',
local: [ 'El último ferry (2.ª ed.)', '17.50' ], patch: { price: '17.50' } }
conflict 12 client
{ id: '12', title: 'El último ferry (2.ª ed.)', price: '17.50', rating: 4.3, year: 2023, category: 'novela-negra' }
With 'client' it resends only the fields of your patch, so the new title survives. Return an object instead and that object goes as the Merge Patch.
openRestepSync(options)Returns a promise of the replica. It throws if the discovery document is not Restep 1, if a collection is not in discovery or is a subcollection, if a synced collection lacks filter on id with in, or if it is offline and has no saved discovery document.
| Option | Default | What it does |
|---|---|---|
url | required | The API root, where the discovery document is |
collections | required | Names of the collections to replicate |
storage | memoryStorage() | Where the replica is saved (below) |
interval | 30000 | Milliseconds between background syncs; 0 turns them off |
autoPush | true | After each local write, try to send the queue straight away |
onConflict | 'server' | 'server', 'client' or a function (below) |
token | none | A string, or a function (async is fine) that returns one, for Authorization: Bearer |
headers | {} | Extra headers on every request, such as Accept-Language |
retry | { base: 1000, max: 60000 } | Exponential backoff between retries, in ms, with some jitter |
timeout | 15000 | Per request, in ms |
fetch | globalThis.fetch | To inject another implementation |
| Method | What it does |
|---|---|
list(name, { filter, sort, limit, offset }) | Local items, queue applied. filter is an object of equalities or a function; sort is 'field', '-field', a comma list, an array of them or a compare function |
get(name, id) | One local item, or null. Takes a provisional id too |
create(name, body) | Queues a POST and returns the item at once, with a local-… id, or the id the client picks where id_from lets it. An id in the body only with id_from "client" or "either"; otherwise it throws |
update(name, id, patch, { onConflict }) | Queues a Merge Patch and returns the item as it now looks. The item must be in the replica |
delete(name, id, { onConflict }) | Queues a DELETE |
sync({ pull, background, retryUncertain }) | Pushes the queue, then pulls changes. One at a time: a second call waits for the first. Never throws for lack of network; returns a report. pull: false only pushes. On demand it retries at once, except where the server asked for Retry-After; background: true respects the backoff, as the timer does. retryUncertain: true sends an uncertain create again, which may duplicate it |
pending() | The queued operations, with attempts, lastError and when they will be retried |
resolveId(name, id) | The server’s id for a provisional one, once it is known |
mode(name) | 'sync' (with :changes) or 'reload' (reloaded in full) |
discard(opId) | Removes an operation from the queue and undoes its local change |
on(event, fn), off(event, fn) | Subscribe and unsubscribe. on() returns the function that unsubscribes |
close() | Stops the timer and resolves when the running sync and the last save have finished |
The report of sync(): { online, pushed, dropped, conflicts, pending, pulled, reset, errors, waitingUntil, uncertain }. pulled counts per collection, reset lists the collections that were reloaded after a 410, waitingUntil appears when a retry is waiting for its time, and uncertain, with an opId, when a create waits for you to decide.
| Event | Payload |
|---|---|
change | { collection, source, created, updated, destroyed }. source is local (your write), push (the server confirmed it; a create adds replaced), remote (pulled; reload: true after a full reload), conflict or rollback |
conflict | { collection, id, type, resolution, base, server, local } |
error | { error, operation }. error is a RestepError with status and problem when it came from the server |
A 412, or a different version when it reads the item first, calls the strategy of the operation: the one given to update or delete, else the one given to openRestepSync.
'server': your change is dropped and the replica takes the server’s version.'client': your change is sent again with the new ETag. On an update, only the fields of your patch.({ collection, id, type, base, server, local, patch }), async if you like. base is the version you saw, server the current one, local the server’s with your patch applied. It returns 'server', 'client' or, on an update, an object to send as the Merge Patch.If the item no longer exists on the server, the server wins. After 3 rounds of conflict on the same operation, too. Functions passed per call live in memory: after a restart, pending operations use the general strategy.
A storage is { read(): Promise<object | null>, write(object): Promise<void> }. It saves the whole replica (discovery, collections, queue) as one JSON object. Fine for thousands of items.
| Storage | Where |
|---|---|
memoryStorage() | In memory, for tests. The default |
fileStorage(path) | A JSON file, in Node. Writes a temporary file and renames it |
indexedDBStorage(name, { store, key }) | One record in IndexedDB, in the browser. Defaults: 'restep-sync', 'replicas', 'default'. Not yet tested in a browser |
sync is experimental: it only uses it under "1.0-draft.6". With any other version of Restep 1, "1.0" included, it reloads collections in full.events (section 10) are not used. It syncs on a timer or when you ask.path with a template and parent, such as /books/{book_id}/reviews on the reference server) or singletons: opening one gives a clear error. Replicating one would mean choosing the parent items (one, some or all) and a state for each, and 10 only defines :changes for collections that declare sync.list() are local equalities or functions, with no indexes. Text is sorted by code point; a field that collations declares with a value other than "codepoint" cannot be sorted or filtered locally with an object or a string (6.1): it throws, and a function is up to you.create response is lost and a background sync pulls changes before the retry, the item can show twice (provisional and real) until the retry confirms it. An explicit sync() does not pull after a network failure, so it does not happen there.batch, no actions. update always sends Merge Patch._inherited or any other _ member: it keeps them as data.Browse any Restep API from this site: query forms built from discovery, writes, actions, errors explained and the curl for every request.
A command line client that learns the API from discovery: get, create, update, delete, actions, every page, CSV, and completion in zsh and bash.
A generic Python client, standard library only: iteration over pages, typed values, one exception per error code, async with httpx.