Skip to content

Commit

Permalink
Wrapped event store actions with try catches and connection handling
Browse files Browse the repository at this point in the history
  • Loading branch information
dave committed Feb 8, 2025
1 parent 1eefee2 commit ecf7829
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions src/packages/emmett-sqlite/src/eventStore/SQLiteEventStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,22 @@ export const getSQLiteEventStore = (
let state = initialState();

if (typeof streamName !== 'string') {
throw new Error('not string');
throw new Error('Stream name is not string');
}

if (db == null) {
db = createConnection();
}

const result = await readStream<EventType>(db, streamName, options.read);

let result;
try {
result = await readStream<EventType>(db, streamName, options.read);
} catch (err: Error) {
closeConnection();
throw err;
} finally {
closeConnection();
}
const currentStreamVersion = result.currentStreamVersion;

assertExpectedVersionMatchesCurrent(
Expand All @@ -137,8 +144,6 @@ export const getSQLiteEventStore = (
state = evolve(state, event);
}

closeConnection();

return {
currentStreamVersion: currentStreamVersion,
state,
Expand All @@ -157,9 +162,15 @@ export const getSQLiteEventStore = (
}

await ensureSchemaExists();
const stream = await readStream<EventType>(db, streamName, options);

closeConnection();
let stream;
try {
stream = await readStream<EventType>(db, streamName, options);
} catch (err: Error) {
closeConnection();
throw err;
} finally {
closeConnection();
}
return stream;
},

Expand All @@ -179,15 +190,21 @@ export const getSQLiteEventStore = (
const streamType =
firstPart && rest.length > 0 ? firstPart : 'emt:unknown';

const appendResult = await appendToStream(
db,
streamName,
streamType,
events,
options,
);

closeConnection();
let appendResult;
try {
appendResult = await appendToStream(
db,
streamName,
streamType,
events,
options,
);
} catch (err: Error) {
closeConnection();
throw err;
} finally {
closeConnection();
}

if (!appendResult.success)
throw new ExpectedVersionConflictError<bigint>(
Expand Down

0 comments on commit ecf7829

Please sign in to comment.