@russ-b/nestjs-common-tools
Version:
NestJS utility tools
67 lines • 1.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pagination = void 0;
const common_1 = require("@nestjs/common");
const exceptions_1 = require("./exceptions");
class Pagination {
static params(page, perPage) {
return { perPage, offset: Pagination.offset(page, perPage) };
}
/**
* @deprecated Use params instead.
*/
static paginationParams(page, perPage) {
return Pagination.params(page, perPage);
}
static offset(page, perPage) {
return (page - 1) * perPage;
}
static createResponse({ page, perPage }, [data, total]) {
return {
data,
pagination: Pagination.createMeta(page, perPage, total),
};
}
static createLegacyResponse({ page, perPage }, [data, total]) {
return {
data,
pagination: Pagination.createLegacyMeta(Pagination.createMeta(page, perPage, total)),
};
}
/**
* @deprecated Use createLegacyResponse instead.
*/
static response(pagination, result) {
try {
return Pagination.createLegacyResponse(pagination, result);
}
catch (error) {
if (error instanceof exceptions_1.PaginationOutOfRangeError) {
throw new common_1.BadRequestException(error.message);
}
throw error;
}
}
static createMeta(page, perPage, total) {
const pages = Math.ceil(total / perPage);
if (page > pages && pages > 0) {
throw new exceptions_1.OutOfRangeException();
}
return {
total,
pages,
perPage,
page,
};
}
static createLegacyMeta({ total, pages, page, perPage, }) {
return {
totalItems: total,
totalPages: pages,
perPage,
page,
};
}
}
exports.Pagination = Pagination;
//# sourceMappingURL=pagination.js.map