@squareboat/nestjs-objection
Version:
The objection database package for your NestJS Applications
102 lines (101 loc) • 3.58 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomQueryBuilder = void 0;
const objection_1 = require("objection");
class CustomQueryBuilder extends objection_1.QueryBuilder {
paginate(page, perPage) {
return __awaiter(this, void 0, void 0, function* () {
page = +page ? +page : 1;
perPage = +perPage ? +perPage : 15;
const result = yield this.page(page - 1, perPage);
return {
pagination: {
currentPage: page,
totalPages: Math.ceil(result.total / perPage),
perPage,
total: result.total,
},
data: result.results,
};
});
}
allPages() {
return __awaiter(this, void 0, void 0, function* () {
return { data: (yield this) };
});
}
onlyCount() {
return __awaiter(this, void 0, void 0, function* () {
const result = (yield this.count({ c: "*" }));
return +result[0].c;
});
}
exists() {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.onlyCount();
return !!result;
});
}
chunk(cb, size) {
return __awaiter(this, void 0, void 0, function* () {
let offset = 0;
let hasMore = true;
while (!!!offset || hasMore) {
const query = structuredClone(this);
const records = (yield query
.offset(offset)
.limit(size));
hasMore = !(records.length > 0);
if (!hasMore)
return;
yield cb(records);
offset += size;
}
});
}
cOrderBy(expressions) {
const orders = (expressions || "").split("|");
for (const order of orders) {
const [column, direction] = order.split(":");
if (!column)
continue;
this.orderBy(column, (direction || "ASC"));
}
return this;
}
when(condition, truthyCb, falsyCb) {
if (condition) {
return truthyCb(this, condition);
}
else if (falsyCb) {
return falsyCb(this, condition);
}
else {
return this;
}
}
safeWhereIn(col, expr) {
if (!Array.isArray(expr))
return this;
if (Array.isArray(expr) && expr.length < 1)
return this;
return this.whereIn(col, expr);
}
safeWhereNotIn(col, expr) {
if (!Array.isArray(expr))
return this;
if (Array.isArray(expr) && expr.length < 1)
return this;
return this.whereNotIn(col, expr);
}
}
exports.CustomQueryBuilder = CustomQueryBuilder;