@sonibble-creators/nest-microservice-pack
Version:
Microservice pack dependencies for NestJS
56 lines • 2.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPagingParameters = void 0;
const graphql_relay_1 = require("graphql-relay");
const getId = (cursor) => parseInt((0, graphql_relay_1.fromGlobalId)(cursor).id, 10);
const nextId = (cursor) => getId(cursor) + 1;
function getPagingParameters(args) {
const meta = checkPagingSanity(args);
switch (meta.pagingType) {
case 'forward': {
return {
limit: meta.first,
offset: meta.after ? nextId(meta.after) : 0,
};
}
case 'backward': {
const { last, before } = meta;
let limit = last;
let offset = getId(before) - last;
if (offset < 0) {
limit = Math.max(last + offset, 0);
offset = 0;
}
return { offset, limit };
}
default:
return {
limit: 8,
offset: 0,
};
}
}
exports.getPagingParameters = getPagingParameters;
function checkPagingSanity(args) {
const { first = 0, last = 0, after, before } = args;
const isForwardPaging = !!first || !!after;
const isBackwardPaging = !!last || !!before;
if (isForwardPaging && isBackwardPaging) {
throw new Error('Relay pagination cannot be forwards AND backwards!');
}
if ((isForwardPaging && before) || (isBackwardPaging && after)) {
throw new Error('Paging must use either first/after or last/before!');
}
if ((isForwardPaging && first < 0) || (isBackwardPaging && last < 0)) {
throw new Error('Paging limit must be positive!');
}
if (last && !before) {
throw new Error("When paging backwards, a 'before' argument is required!");
}
return isForwardPaging
? { pagingType: 'forward', after, first }
: isBackwardPaging
? { pagingType: 'backward', before, last }
: { pagingType: 'none' };
}
//# sourceMappingURL=pagination.js.map