all files / axway/lib/ pager.js

97.38% Statements 186/191
93.81% Branches 91/97
100% Functions 0/0
99.41% Lines 169/170
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                                        11× 11× 11× 11× 11× 10× 10× 11× 11×   11× 11× 11× 11×   11× 11×   11× 11× 11× 11×   11×                                                                                                                         10× 10× 10× 10× 10× 82× 82× 82× 73× 73× 73×   82× 72×     10×                                                                                                              
'use strict';
 
const _ = require('lodash');
const async = require('async');
const url = require('url');
const util = require('./util');
 
// Takes a function(context, finalizedOutput), and returns a new
// function(context, unfinalizedOutput).
exports.page = (send) => {
  return (context, output) => {
    if ((output.resource.parameters || []).filter(p =>
        (p.name === 'page' || p.name === 'pageSize') &&
        p.type === 'query').length === 0) {
      return send(context, output.finalize());
    }
 
    const errStrategy = createStrategy(output);
    const err = errStrategy[0]; const strategy = errStrategy[1];
    if (util.notNull(err) || !util.notNull(strategy)) {
      return context.fail(util.failure(400,
          `Can't determine paging strategy: ${err}`));
    }
 
    let objs = [];
    async.during(
      cb => {
        let innerContext = _.assign(_.clone(context), {
          succeed: data => strategy.hasMore(objs, data, cb),
          fail: failure => cb(failure),
          done: (err, data) => {
            Iif (util.notNull(err)) { cb(err); }
            else { strategy.hasMore(objs, data, cb); }
          }
        });
 
        let innerOutput = _.cloneDeep(output).finalize(strategy.input());
        send(innerContext, innerOutput);
      },
      cb => cb(),   // noop: all the work is done in the test
      failure => {
        if (util.notNull(failure)) { return context.fail(failure); }
        else {
          return context.succeed(convertMerged(output, strategy, objs));
        }
      }
    );
  };
};
 
// Find a pagination strategy that lets us iterate through all the
// backend requests to get the data that we need to return.
const createStrategy = (output) => {
  const inQuery = output.input.queryParameters || {};
  const nextDetails = util.decodeJson64(inQuery.nextPage) || {};
  let isCursor = false;
  let page = inQuery.page;
  if (!util.notNull(page)) {
    page = nextDetails.page;
    isCursor = true;
  } else { page -= 1; }
  if (!util.notNull(page)) { page = 0; }
  page = Math.max(0, page);
 
  let pageSize = inQuery.pageSize;
  if (!util.notNull(pageSize)) { pageSize = nextDetails.pageSize; }
  if (!util.notNull(pageSize)) { pageSize = 50; }
  pageSize = Math.max(0, pageSize);
 
  nextDetails.page = page;
  nextDetails.pageSize = pageSize;
 
  const pageType = output.findConfig('pagination.type') || 'page';
  const pageMax = output.findConfig('pagination.max') || 200;
  const start = page * pageSize;
  const end = (page + 1) * pageSize;
 
  if (pageType === 'offset') {
    return [null, offsetStrategy(page, pageSize, start, end, pageMax)];
  } else if (pageType === 'page') {
    let startInd = parseInt(output.findConfig('pagination.page.startindex'));
    if (isNaN(startInd)) { startInd = 1; }
    return [null, pageStrategy(page, pageSize, start, end, pageMax, startInd, isCursor)];
  } else if (pageType === 'cursor') {
    let offset = nextDetails.offset;
    let cursor = nextDetails.providerNextPage;
    if (!util.notNull(offset)) {
      offset = nextDetails.page * nextDetails.pageSize;
    }
    const nextPageKey = output.resource.nextPageKey;
    if (!util.notNull(nextPageKey)) {
      return ["unable to use cursor: no nextPageKey"];
    }
    return [null, cursorStrategy(page, pageSize, start, end, pageMax,
        cursor, offset, nextPageKey)];
  }
};
exports.createStrategy = (output) => createStrategy(output);
 
// An offset strategy asks the backend for a particular offset and
// limit, as often needed until all results are in. Offsets are always
// zero-based, so an offset of 0 is the same as asking for no offset at
// all.
const offsetStrategy = (page, pageSize, start, end, max) => {
  let offset = start;
  let limit = Math.min(max, end - offset);
  let lastHeaders = {};
  let hasMore = true;
 
  return {
    hasMore: (objs, data, cb) => {
      lastHeaders = data.headers;
      // TODO : check response header or something?
      hasMore = (data.body || []).length >= limit;
      objs.push.apply(objs, data.body);
      offset += (data.body || []).length;
      limit = Math.min(max, end - offset);
      return cb(null, hasMore && offset < end);
    },
    input: () => ({ queryParameters: { page: offset, pageSize: limit } }),
    headers: () => lastHeaders,
    cursor: () => {
      if (!hasMore) return null;
      return ({
        page: page + 1,
        pageSize: pageSize,
        offset: offset
      });
    }
  };
};
exports.offsetStrategy = (page, pageSize, start, end, max) => offsetStrategy(page, pageSize, start, end, max);
 
// A page strategy asks the backend for a particular page and pageSize,
// possibly multiple times, finding the optimal page and pageSize every
// request. The 'startInd' argument indicates which index the backend
// thinks is the first record, and is usually 1 (for 1-based-index
// backends) or 0 (for 0-based-index backends).
const pageStrategy = (page, pageSize, start, end, max, startInd, isCursor) => {
  let offset = start;
  let optimal = optimalPaging(offset, end, max);
  let lastHeaders = {};
  let hasMore = true;
  // non-cursor has been decremented
  let incrementNumber = isCursor ? 1 : 2 ;
 
  return {
    hasMore: (objs, data, cb) => {
      lastHeaders = data.headers;
      // TODO : check response header or something?
      if(util.notNull(data.body) && Array.isArray(data.body)) {
        hasMore = data.body.length >= optimal.pageSize;
        objs.push.apply(objs, data.body.slice(optimal.slice));
        offset = optimal.page * optimal.pageSize + data.body.length;
        optimal = optimalPaging(offset, end, max);
        return cb(null, hasMore && offset < end);
      }
      return cb(null, false);
    },
    input: () => ({ queryParameters: shiftIndex(optimal, startInd) }),
    headers: () => lastHeaders,
    cursor: () => {
      Iif (!hasMore) return null;
      return ({
        page: page + incrementNumber,
        pageSize: pageSize,
        offset: offset
      });
    }
  };
};
exports.pageStrategy = (page, pageSize, start, end, max, startInd, isCursor) => pageStrategy(page, pageSize, start, end, max, startInd, isCursor);
 
// Find a pageSize that maximizes:
//
//     min(end, (pageSize * (page + 1)))
//     where page = floor(offset / pageSize)
//         , pageSize <= max
//
// Where multiple pageSize values have the same score, we want to choose
// the smallest one.
//
// For example, if offset=55, end=75, max=10, the optimal pageSize is
// 9 which returns items 54-62: 8 of which are values we care about,
// and not (as one might naively suspect) 10 which gets items 50-59,
// of which only 5 we care about.
//
const optimalPaging = (offset, end, max) => {
  // start with max size, and go downward until
 
  // TODO : use prime factorization combinatorics instead?
  let pageSize = Math.min(max, (end - offset) * 2);
  let bestPage;
  let bestPageSize;
  let maxCapture = 0;
  while (pageSize > 0) {
    let page = Math.floor(offset / pageSize);
    let capture = Math.min(end, pageSize * (page + 1));
    if (capture >= maxCapture) {
      maxCapture = capture;
      bestPage = page;
      bestPageSize = pageSize;
    }
    if (maxCapture >= pageSize + offset) break;
    --pageSize;
  }
 
  return {
    page: bestPage,
    pageSize: bestPageSize,
    slice: offset - bestPageSize * bestPage
  };
};
exports.optimalPaging = (offset, end, max) => optimalPaging(offset, end, max);
 
const shiftIndex = (optimal, startInd) => {
  return {page: optimal.page + startInd, pageSize: optimal.pageSize};
};
exports.shiftIndex = (optimal, startInd) => shiftIndex(optimal, startInd);
 
// A cursor strategy sends a cursor to the backend, which is a
// continuation token that resumes record retrieval at some offset
// indicated by 'cOffset'.
//
const cursorStrategy = (page, pageSize, start, end, max, cursor, cOffset,
    nextPageKey) => {
  let offset = cOffset;
  if (offset > start) {
    // boo, restart from the top
    offset = 0;
    cursor = null;
  }
  let slice = start - offset;
  let size = Math.min(max, end - offset);
  let lastHeaders = {};
 
  return {
    hasMore: (objs, data, cb) => {
      lastHeaders = data.headers;
      extractCursor(data, nextPageKey, (err, gotCursor) => {
        Iif (util.notNull(err)) { return cb(err); }
        cursor = gotCursor;
        Eif(util.notNull(data.body)) {
          offset += data.body.length;
          //If the results is an array then add the results to the obj,
          //if its an object then just insert the object to objs
          if(data.body instanceof Array) {
            objs.push.apply(objs, data.body.slice(slice));
          } else {
            objs.push(data.body);
          }
        }
        if (start > offset) { slice = start - offset; }
        else { slice = 0; }
        size = Math.min(max, end - offset);
        return cb(null, util.notNull(cursor) && offset < end);
      });
    },
    input: () => ({ queryParameters: { pageSize: size, nextPage: cursor }}),
    headers: () => lastHeaders,
    cursor: () => {
      Iif (!util.notNull(cursor)) return null;
      return ({
        page: page + 1,
        pageSize: pageSize,
        offset: offset,
        providerNextPage: cursor
      });
    }
  };
};
exports.cursorStrategy = (page, pageSize, start, end, max, cursor, cOffset, nextPageKey) => cursorStrategy(page, pageSize, start, end, max, cursor, cOffset, nextPageKey);
 
// Extract a cursor from a response. The 'nextPageKey' determines
// where in the response to find the cursor, and can be
//
//    * `header.<header_name>` : found as a header
//    * `body.<body_location>` : found as a body value
//    * `body.<body_location>?queryParam : query param on a body value
//
const extractCursor = (data, nextPageKey, cb) => {
  if (nextPageKey.startsWith("header.")) {
    nextPageKey = nextPageKey.substr(7);
    cb(null, (data.headers || {})[nextPageKey]);
  } else if (nextPageKey.startsWith("body.")) {
    nextPageKey = nextPageKey.substr(5);
    let q = nextPageKey.indexOf('?');
    let query = null;
    if (q !== -1) {
      query = nextPageKey.substr(q + 1);
      nextPageKey = nextPageKey.substr(0, q);
    }
    let val = _.get((data.originalBody || data.body), nextPageKey);
    if (util.notNull(query) && util.notNull(val)) {
      val = url.parse(val, true).query[query];
    }
    cb(null, val);
  } else {
    cb(util.failure(500, `Unknown nextPageKey format: ${nextPageKey}`));
  }
};
exports.extractCursor = (data, nextPageKey, cb) => extractCursor(data, nextPageKey, cb);
 
const convertMerged = (output, strategy, objs) => {
  let headers = strategy.headers() || {};
  headers["Elements-Returned-Count"] = objs.length;
 
  let cursor;
  if (util.notNull(cursor = strategy.cursor())) {
    headers["Elements-Next-Page-Token"] = util.encodeJson64(cursor);
  }
 
  return {
    body: objs,
    headers: headers
  };
};
exports.convertMerged = (output, strategy, objs) => convertMerged(output, strategy, objs);