server/helpers/collections.js

"use strict";

require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/es.weak-map.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCollectionItems = getCollectionItems;
exports.getOrderedCollectionsForEditorPage = getOrderedCollectionsForEditorPage;
exports.getOrderedPublicCollections = getOrderedPublicCollections;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
require("core-js/modules/es.parse-int.js");
require("core-js/modules/es.date.to-json.js");
require("core-js/modules/web.url.to-json.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/web.dom-collections.for-each.js");
require("core-js/modules/es.array.concat.js");
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var error = _interopRequireWildcard(require("../../common/helpers/error"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright (C) 2020 Prabal Singh
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
/**
 * Fetches collections of an Editor
 * Fetches the last 'size' collections with offset 'from'
 *
 * @param {number} from - the offset value
 * @param {number} size - no. of last collections required
 * @param {string} entityType - entityType filter
 * @param {object} req - req is an object containing information about the HTTP request
 * @returns {array} - orderedCollections for particular Editor
 * @description
 * This checks whether Editor is valid or not.
 * If Editor is valid then this extracts and returns collections of that editor;
 * If the user is not the editor, then only "Public' collections are returned
 */
function getOrderedCollectionsForEditorPage(_x, _x2, _x3, _x4) {
  return _getOrderedCollectionsForEditorPage.apply(this, arguments);
}
/**
 * Fetches public collections for Show All Collections/Index Page
 * Fetches the last 'size' number of collections with offset 'from'
 *
 * @param {number} from - the offset value
 * @param {number} size - no. of last collections required
 * @param {string} entityType - entityType filter
 * @param {object} orm - the BookBrainz ORM, initialized during app setup
 * @returns {array} - orderedCollections
 */
function _getOrderedCollectionsForEditorPage() {
  _getOrderedCollectionsForEditorPage = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(from, size, entityType, req) {
    var _req$app$locals$orm, Editor, UserCollection, isThisCurrentUser, allCollections, collectionsJSON;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _req$app$locals$orm = req.app.locals.orm, Editor = _req$app$locals$orm.Editor, UserCollection = _req$app$locals$orm.UserCollection; // If editor isn't present, throw an error
            _context.next = 3;
            return new Editor({
              id: req.params.id
            }).fetch().catch(Editor.NotFoundError, function () {
              throw new error.NotFoundError('Editor not found', req);
            });
          case 3:
            isThisCurrentUser = req.user && parseInt(req.params.id, 10) === parseInt(req.user.id, 10);
            _context.next = 6;
            return new UserCollection().query(function (qb) {
              qb.leftJoin('bookbrainz.user_collection_collaborator', 'bookbrainz.user_collection.id', '=', 'bookbrainz.user_collection_collaborator.collection_id');
            }).where(function (builder) {
              if (!isThisCurrentUser) {
                builder.where('public', true);
              }
              if (entityType) {
                builder.where('entity_type', entityType);
              }
            }).where(function (builder) {
              builder.where('collaborator_id', '=', req.params.id).orWhere('owner_id', '=', req.params.id);
            }).orderBy('created_at').fetchPage({
              limit: size,
              offset: from,
              withItemCount: true
            });
          case 6:
            allCollections = _context.sent;
            collectionsJSON = allCollections ? allCollections.toJSON() : [];
            collectionsJSON.forEach(function (collection) {
              collection.isOwner = parseInt(req.params.id, 10) === collection.ownerId;
            });
            return _context.abrupt("return", collectionsJSON);
          case 10:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _getOrderedCollectionsForEditorPage.apply(this, arguments);
}
function getOrderedPublicCollections(_x5, _x6, _x7, _x8) {
  return _getOrderedPublicCollections.apply(this, arguments);
}
/**
 * Fetches bbids of entities in the collection
 * Fetches the last 'size' number of bbids with offset 'from'
 * @param {uuid} collectionId - collectionId
 * @param {number} from - the offset value
 * @param {number} size - no. of last collections required
 * @param {object} orm - the BookBrainz ORM, initialized during app setup
 * @returns {array} - array of bbids
 */
function _getOrderedPublicCollections() {
  _getOrderedPublicCollections = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(from, size, entityType, orm) {
    var UserCollection, allCollections, collectionsJSON;
    return _regenerator.default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            UserCollection = orm.UserCollection;
            _context2.next = 3;
            return new UserCollection().where(function (builder) {
              builder.where('public', true);
              if (entityType) {
                builder.where('entity_type', entityType);
              }
            }).orderBy('last_modified', 'DESC').fetchPage({
              limit: size,
              offset: from,
              withItemCount: true,
              withRelated: ['owner']
            });
          case 3:
            allCollections = _context2.sent;
            collectionsJSON = allCollections ? allCollections.toJSON() : [];
            return _context2.abrupt("return", collectionsJSON);
          case 6:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _getOrderedPublicCollections.apply(this, arguments);
}
function getCollectionItems(_x9, _x10, _x11, _x12) {
  return _getCollectionItems.apply(this, arguments);
}
function _getCollectionItems() {
  _getCollectionItems = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3(collectionId, from, size, orm) {
    var result;
    return _regenerator.default.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return orm.bookshelf.knex.raw("\n\t\t\t\t\t\tSELECT bookbrainz.user_collection_item.bbid,\n\t\t\t\t\t\tbookbrainz.user_collection_item.added_at\n\t\t\t\t\t\tFROM bookbrainz.user_collection_item\n\t\t\t\t\t\tWHERE collection_id='".concat(collectionId, "'\n\t\t\t\t\t\tORDER BY user_collection_item.added_at ASC\n\t\t\t\t\t\tLIMIT ").concat(size, "\n\t\t\t\t\t\tOFFSET ").concat(from));
          case 2:
            result = _context3.sent;
            return _context3.abrupt("return", result.rows);
          case 4:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _getCollectionItems.apply(this, arguments);
}
//# sourceMappingURL=collections.js.map