Skip to content

Commit

Permalink
Use secondary nodes of your MongoDB cluster to calculate balances
Browse files Browse the repository at this point in the history
  • Loading branch information
koresar committed Apr 21, 2023
1 parent 2a8c906 commit 35fa920
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
10 changes: 10 additions & 0 deletions src/Book.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ export class Book<U extends ITransaction = ITransaction, J extends IJournal = IJ
}

async balance(query: IBalanceQuery, options = {} as IOptions): Promise<{ balance: number; notes: number }> {
if (options) {
// If there is a session, we must NOT set any readPreference (as per mongo v5 and v6).
// https://www.mongodb.com/docs/v6.0/core/transactions/#read-concern-write-concern-read-preference
// Otherwise, we are free to use any readPreference.
if (!options.session && !options.readPreference) {
// Let's try reading from the secondary node, if available.
options.readPreference = "secondaryPreferred";
}
}

const parsedQuery = parseBalanceQuery(query, this);
const meta = parsedQuery.meta;
delete parsedQuery.meta;
Expand Down
2 changes: 2 additions & 0 deletions src/IOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { ClientSession } from "mongoose";
import { ReadPreferenceLike } from "mongodb";

// aggregate of mongoose expects Record<string, unknown> type
export type IOptions = {
session?: ClientSession;
readPreference?: ReadPreferenceLike;
};
5 changes: 1 addition & 4 deletions src/models/balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,5 @@ export async function snapshotBalance(
export function getBestSnapshot(query: FilterQuery<IBalance>, options: IOptions = {}): Promise<IBalance | null> {
const { book, account, meta, ...extras } = query;
const key = hashKey(constructKey(book, account, { ...meta, ...extras }));
return balanceModel.collection.findOne(
{ key },
{ sort: { _id: -1 }, session: options.session }
) as Promise<IBalance | null>;
return balanceModel.collection.findOne({ key }, { sort: { _id: -1 }, ...options }) as Promise<IBalance | null>;
}

0 comments on commit 35fa920

Please sign in to comment.