objection-paginator
Version:
Paginated queries for Objection.js
92 lines • 3.41 kB
JavaScript
import { ColumnType, SortDirection } from "./sort-descriptor.js";
import { ValidationCase, getErrorClass } from "./get-error-class.js";
import _ from "lodash";
import { Column } from "./column.js";
import { ConfigurationError } from "./configuration-error.js";
import objectPath from "object-path";
export class ConcreteSortDescriptor {
constructor(descriptor) {
if (_.isString(descriptor))
descriptor = { column: descriptor };
_.defaults(this, descriptor, {
columnType: ColumnType.String,
nullable: false,
direction: SortDirection.Ascending,
valuePath: descriptor.column,
});
Column.validate(this.column);
if (!Object.values(ColumnType).includes(this.columnType)) {
throw new ConfigurationError(`Unknown column type '${this.columnType}'`);
}
if (!Object.values(SortDirection).includes(this.direction)) {
throw new ConfigurationError(`Unknown sort direction '${this.direction}'`);
}
}
get order() {
const { direction } = this;
if (direction === SortDirection.DescendingNullsLast) {
return SortDirection.Descending;
}
return direction;
}
get nullOrder() {
const { direction } = this;
if (direction === SortDirection.DescendingNullsLast) {
return SortDirection.Ascending;
}
return direction;
}
get operator() {
return this.direction === SortDirection.Ascending ? ">" : "<";
}
checkCursorValue(value) {
switch (this.columnType) {
case ColumnType.String:
return _.isString(value);
case ColumnType.Integer:
return _.isInteger(value);
case ColumnType.Float:
return _.isFinite(value);
case ColumnType.Boolean:
return _.isBoolean(value);
case ColumnType.Date:
return value instanceof Date || _.isString(value);
default:
return false;
}
}
validateCursorValue(value, validationCase) {
if (value === null) {
if (!this.nullable) {
throw new (getErrorClass(validationCase))("Cursor value is null, but column is not nullable", { info: { value: null } });
}
}
else if (!this.checkCursorValue(value)) {
throw new (getErrorClass(validationCase))("Cursor value does not match its column type", { info: { value, columnType: this.columnType } });
}
const validateResult = this.validate ? this.validate(value) : true;
let isValid;
let msg;
if (_.isString(validateResult)) {
isValid = false;
msg = validateResult;
}
else {
isValid = validateResult;
msg = "Invalid cursor value";
}
if (isValid)
return value;
throw new (getErrorClass(validationCase))(msg, { info: { value } });
}
getCursorValue(entity) {
let value = objectPath.get(entity, this.valuePath);
if (value === undefined)
value = null;
return this.validateCursorValue(value, ValidationCase.Configuration);
}
getRawColumn(qry) {
return Column.toRaw(this.column, qry);
}
}
//# sourceMappingURL=concrete-sort-descriptor.js.map