UNPKG

@conpago/mongo-cursor-pagination

Version:

Make it easy to return cursor-paginated results from a Mongo collection

34 lines 1.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decode = exports.encode = void 0; const bson_1 = require("bson"); // BSON can't encode undefined values, so we will use this value instead: const BSON_UNDEFINED = "__mixmax__undefined__"; /** * These will take a paging handle (`next` or `previous`) and encode/decode it * as a string which can be passed in a URL. */ function _encode(str) { return Buffer.from(encodeURIComponent(str)).toString("base64"); } function _decode(str) { return decodeURIComponent(Buffer.from(str, "base64").toString()); } const encode = (obj) => { if (Array.isArray(obj) && obj[0] === undefined) obj[0] = BSON_UNDEFINED; else if (typeof obj === "string" && obj === "") return obj; return _encode(typeof obj === "string" ? obj : bson_1.EJSON.stringify(obj, { relaxed: true })); }; exports.encode = encode; const decode = (str) => { if (str === "") return str; const obj = bson_1.EJSON.parse(_decode(str), { relaxed: true }); if (Array.isArray(obj) && obj[0] === BSON_UNDEFINED) obj[0] = undefined; return obj; }; exports.decode = decode; //# sourceMappingURL=bsonUrlEncoding.js.map