UNPKG

@sauce-api/core

Version:

Sauce API core functionality

84 lines (83 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Service = void 0; const utility_1 = require("./utility"); /** * A Service class that provides utility functions for handling requests */ class Service { constructor(Sauce) { var _a, _b; this.Sauce = Sauce; this.req = Sauce.req; this.currentRoute = Sauce.currentRoute; this.res = Sauce.res; this.next = Sauce.next; this.route = Sauce.currentRoute; this.config = Sauce.config; this.paging = { page: 1, pageSize: ((_a = this.config.pagination) === null || _a === void 0 ? void 0 : _a.pageSize) || 25, max: ((_b = this.config.pagination) === null || _b === void 0 ? void 0 : _b.max) || 50 }; } /** * Check if the current route has pagination query params * @return {boolean} - Returns true if current route has pagination query params, false otherwise */ routeHasPagination() { return this.currentRoute.hasQueryParam("page") && this.currentRoute.hasQueryParam("pageSize"); } /** * Builds a pagination query object from the request query params * @throws Will throw an error if pagination query params not configured for the route * @return {PaginationQuery} - Returns a pagination query object */ buildPaginationQuery() { if (this.routeHasPagination()) { this.paging.page = this.req.query["page"] || this.paging.page; this.paging.pageSize = this.req.query["pageSize"] || this.paging.pageSize; if (this.paging.pageSize > this.paging.max) { throw (0, utility_1.formatError)(400, `Page size can not exceed ${this.paging.max}`); } return { limit: this.paging.pageSize, skip: (this.paging.page - 1) * this.paging.pageSize }; } throw new Error("Pagination params not configured for this route"); } /** * Builds a paginated object from an array of data and total number of records * @param {any[]} data - The array of data to paginate * @param {number} [total] - The total number of records * @return {PaginatedObject} - Returns a paginated object */ paginate(data, total) { const host = (0, utility_1.getAppUrl)(this.config); const url = `${host}${this.req.path}`; const queryKeys = this.currentRoute.queryParamKeys; let args = ""; for (let i = 0; i < queryKeys.length; i++) { const param = queryKeys[i]; if (param !== "page" && param !== "pageSize") { if (this.req.query[param]) { args += `${param}=${this.req.query[param]}&`; } } } const next = data.length < this.paging.pageSize ? "" : `${url}?${args}page=${this.paging.page + 1}&pageSize=${this.paging.pageSize}`; const prev = this.paging.page == 1 ? "" : `${url}?${args}page=${this.paging.page - 1}&pageSize=${this.paging.pageSize}`; return { data, page: { size: data.length, prev: prev, current: this.paging.page, next: next, ...(total && { totalPages: Math.ceil(total / this.paging.pageSize) }) } }; } } exports.Service = Service;