@tjercus/pico-event-store@0.2.0
latest
It is unknown whether this package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers




JSR Score
70%
Published
a month ago (0.2.0)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { FSDB, FSDBError } from "npm:file-system-db@2.1.0"; import { type Either, Left, Right } from "npm:purify-ts@2.1.0"; export type PicoEventStore = { appendToStream: <T>( streamName: string, event: T, ) => Either<FSDBError, Array<T>>; createStream: <T>(streamName: string) => Either<FSDBError, Array<T>>; getStreamVersion: (streamName: string) => Either<FSDBError, number>; readStream: <T>(streamName: string) => Either<FSDBError, Array<T>>; }; /** * Simplest implementation of an Event Store using file-system-db */ const PicoEventStoreImpl = ( storageDir: string = "storage", ): PicoEventStore => ({ appendToStream: <T>(streamName: string, event: T) => { try { const db = new FSDB(`./${storageDir}/${streamName}.json`, false); if (db.getAll().length === 0) { PicoEventStoreImpl().createStream(streamName); } db.push(streamName, event); return Right(db.getAll()[0].value as unknown as Array<T>); } catch (ex: unknown) { return Left(ex as FSDBError); } }, createStream: <T>(streamName: string) => { try { const db = new FSDB(`./${storageDir}/${streamName}.json`, false); db.set(streamName, []); return Right(db.getAll()[0].value as unknown as Array<T>); } catch (ex: unknown) { return Left(ex as FSDBError); } }, getStreamVersion: (streamName: string) => { try { const db = new FSDB(`./${storageDir}/${streamName}.json`, false); return Right(db.get(streamName).length); } catch (ex: unknown) { return Left(ex as FSDBError); } }, readStream: <T>(streamName: string) => { try { const db = new FSDB(`./${storageDir}/${streamName}.json`, false); const arr = db.get(streamName); return Array.isArray(arr) ? Right(arr as unknown as Array<T>) : Left( new FSDBError({ message: "Stream not found", method: "readStream" }), ); } catch (ex: unknown) { return Left(ex as FSDBError); } }, }); export default PicoEventStoreImpl;