UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

60 lines (59 loc) 2.72 kB
import { notOptional } from "../util/optional.js"; /** Write a single change to a synchronous provider and return an array of the changes that were written. */ export function writeChange(provider, change) { const { action, collection, id, query } = change; if (action === "add") { // `add` change returns a `set` change so it includes the ID to reflect the change that was written. return { action: "set", collection, id: provider.addItem(collection, change.data), data: change.data }; } if (id) { if (action === "set") provider.setItem(collection, id, change.data); else if (action === "update") provider.updateItem(collection, id, change.updates); else if (action === "delete") provider.deleteItem(collection, id); } else if (query) { if (action === "set") provider.setQuery(collection, query, change.data); else if (action === "update") provider.updateQuery(collection, query, change.updates); else if (action === "delete") provider.deleteQuery(collection, query); } return change; } /** Write a set of changes to a synchronous provider. */ export function writeChanges(provider, ...changes) { return changes.filter(notOptional).map(change => writeChange(provider, change)); } /** Write a single change to an asynchronous provider and return the change that was written. */ export async function writeAsyncChange(provider, change) { const { collection, action, id, query } = change; if (action === "add") { // `add` change returns a `set` change so it includes the ID to reflect the change that was written. return { action: "set", collection, id: await provider.addItem(collection, change.data), data: change.data }; } if (id) { if (action === "set") await provider.setItem(collection, id, change.data); else if (action === "update") await provider.updateItem(collection, id, change.updates); else if (action === "delete") await provider.deleteItem(collection, id); } else if (query) { if (action === "set") await provider.setQuery(collection, query, change.data); else if (action === "update") await provider.updateQuery(collection, query, change.updates); else if (action === "delete") await provider.deleteQuery(collection, query); } return change; } /** Write a set of changes to an asynchronous provider. */ export function writeAsyncChanges(provider, ...changes) { return Promise.all(changes.filter(notOptional).map(change => writeAsyncChange(provider, change))); }