Skip to content

Commit

Permalink
Add 'count' function
Browse files Browse the repository at this point in the history
  • Loading branch information
manelcecs committed Jul 11, 2024
1 parent ef4a0c8 commit eae8ede
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/db/util/raw-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ export type DestroyFn<F extends FieldDefinition> = (args: {

export type TruncateFn = (trx?: Knex.Transaction<any, any>) => Promise<void>;

export type CountFn<F extends FieldDefinition, AdditionalArgs = {}> = (
args?: {
where?: WhereCond<F>;
trx?: Knex.Transaction<any, any>;
distinct?: Array<keyof InstanceDataOf<F>>;
} & AdditionalArgs
) => Promise<number>;

export type ModelInternals<F extends FieldDefinition> = {
readonly type: 'single-table';
readonly tableName: string;
Expand All @@ -94,6 +102,7 @@ export type Model<F extends FieldDefinition, AdditionalFindArgs = {}> = {
readonly update: UpdateFn<F>;
readonly destroy: DestroyFn<F>;
readonly truncate: TruncateFn;
readonly count: CountFn<F, AdditionalFindArgs>;
};

export type InstanceDataOfModel<M extends Model<any>> = M extends Model<infer F>
Expand Down Expand Up @@ -254,6 +263,25 @@ export const defineRawModel =
await builder.truncate();
};

const count: CountFn<F> = async ({ where, trx, distinct } = {}) => {
const builder = trx ? masterTable().transacting(trx) : replicaTable();
const query = builder.where(prepareCondition(where ?? {}));

if (distinct !== undefined) {
query.countDistinct(distinct);
} else {
query.count('*');
}

const res = await query;

const mappedResponse = res as Array<{ count: string }>;

return mappedResponse.length > 0
? parseInt(mappedResponse[0].count, 10)
: 0;
};

return {
_internals: {
type: 'single-table',
Expand All @@ -268,5 +296,6 @@ export const defineRawModel =
update,
destroy,
truncate,
count,
};
};

0 comments on commit eae8ede

Please sign in to comment.