Skip to content

Commit

Permalink
ref(postgres): extract insertCommit
Browse files Browse the repository at this point in the history
  • Loading branch information
theodorton committed Feb 11, 2023
1 parent e275a60 commit d5ef9c4
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions packages/@ddes/postgres/lib/PostgresEventStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,22 @@ export class PostgresEventStore extends EventStore {
}

public async commit<TAggregateCommit extends AggregateCommit>(commit: TAggregateCommit) {
try {
await this.commitOne(this.pool, commit)
} catch (error: any) {
if (error.code === '23505') {
throw new VersionConflictError(commit)
}
throw error
}

return commit
}

private async commitOne<TAggregateCommit extends AggregateCommit>(
pool: Pool,
commit: TAggregateCommit
) {
const {
aggregateType,
aggregateKey,
Expand All @@ -84,8 +100,7 @@ export class PostgresEventStore extends EventStore {
chronologicalKey,
} = commit

try {
const query = sql`INSERT INTO ${sql.ident(this.tableName)} VALUES(
const query = sql`INSERT INTO ${sql.ident(this.tableName)} VALUES(
${aggregateType},
${aggregateKey},
${aggregateVersion},
Expand All @@ -96,15 +111,7 @@ export class PostgresEventStore extends EventStore {
${expiresAt ? new Date(expiresAt) : null}
)`

await this.pool.query(query)
} catch (error: any) {
if (error.code === '23505') {
throw new VersionConflictError(commit)
}
throw error
}

return commit
await pool.query(query)
}

public async *queryAggregateCommits<TAggregateCommit extends AggregateCommit>(
Expand Down

0 comments on commit d5ef9c4

Please sign in to comment.