objection-paginator
Version:
Paginated queries for Objection.js
55 lines • 1.82 kB
JavaScript
import { InvalidJsonError, decodeObject, encodeObject } from "@batterii/encode-object";
import _ from "lodash";
import { InvalidCursorError } from "./invalid-cursor-error.js";
import { is } from "nani";
export class Cursor {
constructor(query, sort, values) {
this.query = query;
this.sort = sort;
this.values = values;
}
static fromObject(obj) {
return new Cursor(obj.q, obj.s, obj.v);
}
static validateObject(value) {
if (!_.isObjectLike(value)) {
throw new InvalidCursorError("Cursor is not object-like", { info: { cursor: value } });
}
if (!_.isString(value.q)) {
throw new InvalidCursorError("Cursor 'q' is not a string", { info: { q: value.q } });
}
if (!_.isString(value.s)) {
throw new InvalidCursorError("Cursor 's' is not a string", { info: { s: value.s } });
}
if (value.v !== undefined && !_.isArray(value.v)) {
throw new InvalidCursorError("Cursor 'v' is not an array", { info: { v: value.v } });
}
return value;
}
static parse(str) {
let obj;
try {
obj = decodeObject(str);
}
catch (err) {
if (!is(err, InvalidJsonError))
throw err;
throw new InvalidCursorError({
shortMessage: "Cursor contains invalid JSON",
cause: err,
info: { cursor: str },
});
}
return Cursor.fromObject(Cursor.validateObject(obj));
}
toObject() {
const obj = { q: this.query, s: this.sort };
if (this.values)
obj.v = this.values;
return obj;
}
serialize() {
return encodeObject(this.toObject());
}
}
//# sourceMappingURL=cursor.js.map