import type { SourceState } from '@wix/bex-core'; import type { EditableTableMutationHandlers } from '../state/EditableTable'; const newLocalId = () => `new-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; /** * Row write handlers read from the source's state — the schema-entry default, * so an editable table needs no `mutations` config. The schema loads before * any row can be added or edited. */ export function sourceMutations( sourceState: SourceState, ): EditableTableMutationHandlers { const backend = () => { const loaded = sourceState.loadedSchema; if (!loaded) { throw new Error('The schema is not loaded yet'); } return loaded.backend; }; const required = (fn: F | undefined, action: string): F => { if (!fn) { throw new Error(`The source doesn't support ${action} items`); } return fn; }; return { createItem: () => ({ [sourceState.schema?.idField ?? '_id']: newLocalId() } as T), submitCreate: (items) => Promise.all( items.map((item) => required(backend().create, 'creating')(item)), ), submitUpdate: (items) => Promise.all( items.map((item) => required(backend().update, 'updating')(item)), ), submitDelete: async (items) => { await required( backend().bulkDelete, 'deleting', )(items.map((item) => sourceState.source.itemKey(item))); }, }; }