import { DBCore , DBCoreMutateRequest , DBCoreMutateResponse , DBCoreTable , Middleware , } from 'dexie' ; import { ulid } from 'ulid' ; export function createUlidMiddleware ( core ) { return { ... core , table ( tableName ) { const table = core . table ( tableName ) ; if ( tableName . startsWith ( '_' ) ) return table ; return { ... table , async mutate ( req ) { switch ( req . type ) { case 'add' : case 'put' : const { primaryKey } = table . schema ; if ( primaryKey . keyPath === '_id' && primaryKey . autoIncrement ) { req . values . forEach ( ( value ) => ( value . _id = value . _id || ulid ( ) ) ) ; } break ; } const res = await table . mutate ( req ) ; return res ; } , } ; } , } ; } export const ulidMiddleware = { stack : 'dbcore' , name : 'UlidMiddleware' , create : createUlidMiddleware , } ;