@cenoa/waas-js-sdk
Version:
Official Cenoa Wallet as a Service SDK
90 lines (89 loc) • 3.58 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const START_OF_LIST = 'START_OF_LIST';
const END_OF_LIST = 'END_OF_LIST';
const EMPTY_LIST = [START_OF_LIST];
class ListHelper {
constructor(fetcherFunction, limit = 5) {
this.limit = limit;
this.lastEvaluatedKeys = EMPTY_LIST;
this.data = [];
this.fetcherFunction = fetcherFunction;
}
getLastEvaluatedKey() {
return this.lastEvaluatedKeys[this.lastEvaluatedKeys.length - 1];
}
hasNext() {
return (this.lastEvaluatedKeys[this.lastEvaluatedKeys.length - 1] !== END_OF_LIST);
}
hasPrevious() {
return this.lastEvaluatedKeys.length > 2;
}
status(isNewFetchedData = false) {
return {
isNewFetchedData,
hasNext: this.hasNext(),
hasPrevious: this.hasPrevious(),
};
}
get() {
return this.data;
}
fetch(evaluatedKey) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetcherFunction({
limit: this.limit,
lastEvaluatedKey: evaluatedKey,
});
});
}
fetchAndUpdateData(evaluatedKey = START_OF_LIST) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
// the end of the list, no need to fetch a new data
if (evaluatedKey === END_OF_LIST) {
return Promise.resolve({
data: this.data,
status: this.status(),
});
}
// fetch new data
const newDataResp = yield this.fetch(evaluatedKey === START_OF_LIST ? undefined : evaluatedKey);
const { list, lastEvaluatedKey } = (_a = newDataResp === null || newDataResp === void 0 ? void 0 : newDataResp.data) !== null && _a !== void 0 ? _a : {};
// update lastEvaluatedKeys stack
this.lastEvaluatedKeys.push(lastEvaluatedKey !== null && lastEvaluatedKey !== void 0 ? lastEvaluatedKey : END_OF_LIST);
// update data
this.data = list !== null && list !== void 0 ? list : [];
// return data and status
return {
data: this.data,
status: this.status(true),
};
});
}
next() {
if (this.hasNext()) {
return this.fetchAndUpdateData(this.getLastEvaluatedKey());
}
return Promise.resolve({ data: this.data, status: this.status() });
}
previous() {
if (this.hasPrevious()) {
// discard last two items
this.lastEvaluatedKeys.pop();
this.lastEvaluatedKeys.pop();
return this.fetchAndUpdateData(this.getLastEvaluatedKey());
}
return Promise.resolve({ data: this.data, status: this.status() });
}
}
exports.default = ListHelper;