server/helpers/collectionRouteUtils.js

"use strict";

require("core-js/modules/es.weak-map.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.collectionCreateOrEditHandler = collectionCreateOrEditHandler;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
require("core-js/modules/es.symbol.js");
require("core-js/modules/es.symbol.description.js");
require("core-js/modules/es.function.name.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.iterator.js");
require("core-js/modules/es.promise.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.date.to-json.js");
require("core-js/modules/web.url.to-json.js");
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _upperFirst2 = _interopRequireDefault(require("lodash/upperFirst"));
var _toLower2 = _interopRequireDefault(require("lodash/toLower"));
var _isEqual2 = _interopRequireDefault(require("lodash/isEqual"));
var _differenceWith2 = _interopRequireDefault(require("lodash/differenceWith"));
var _camelCase2 = _interopRequireDefault(require("lodash/camelCase"));
var search = _interopRequireWildcard(require("../../common/helpers/search"));
var _error = require("../../common/helpers/error");
var _log = _interopRequireDefault(require("log"));
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.
 */
/**
 * A handler for create or edit actions on collections.
 * @param {object} req - request object
 * @param {object} res - response object
 * @param {object} next - next object
 * @returns {promise} res.send promise
 * @description
 * Creates a new collection or updates the existing collection
 * If it's a new collection or it's name is changed, ElasticSearch index is also updated
 */
function collectionCreateOrEditHandler(_x, _x2, _x3) {
  return _collectionCreateOrEditHandler.apply(this, arguments);
}
function _collectionCreateOrEditHandler() {
  _collectionCreateOrEditHandler = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(req, res, next) {
    var _req$app$locals$orm, UserCollection, UserCollectionCollaborator, isNew, newCollection, method, _res$locals$collectio, _res$locals$collectio2, oldCollaborators, newCollaborators, newlyAddedCollaborators, removedCollaborators, collaboratorPromises;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _req$app$locals$orm = req.app.locals.orm, UserCollection = _req$app$locals$orm.UserCollection, UserCollectionCollaborator = _req$app$locals$orm.UserCollectionCollaborator;
            isNew = !res.locals.collection;
            if (!isNew) {
              _context.next = 10;
              break;
            }
            _context.next = 6;
            return new UserCollection({
              ownerId: req.user.id
            });
          case 6:
            newCollection = _context.sent;
            method = 'insert';
            _context.next = 17;
            break;
          case 10:
            if (!((_res$locals$collectio = res.locals.collection) !== null && _res$locals$collectio !== void 0 && (_res$locals$collectio2 = _res$locals$collectio.items) !== null && _res$locals$collectio2 !== void 0 && _res$locals$collectio2.length && (0, _upperFirst2.default)((0, _camelCase2.default)(req.body.entityType)) !== res.locals.collection.entityType)) {
              _context.next = 12;
              break;
            }
            throw new _error.BadRequestError('Trying to change entityType of a non empty collection');
          case 12:
            _context.next = 14;
            return new UserCollection({
              id: req.params.collectionId
            }).fetch({
              require: true
            });
          case 14:
            newCollection = _context.sent;
            method = 'update';
            newCollection.set('last_modified', new Date());
          case 17:
            newCollection.set('description', req.body.description);
            newCollection.set('name', req.body.name);
            newCollection.set('public', (0, _toLower2.default)(req.body.privacy) === 'public');
            newCollection.set('entity_type', (0, _upperFirst2.default)((0, _camelCase2.default)(req.body.entityType)));
            _context.next = 23;
            return newCollection.save(null, {
              method: method
            });
          case 23:
            oldCollaborators = res.locals.collection ? res.locals.collection.collaborators : [];
            newCollaborators = req.body.collaborators ? req.body.collaborators : [];
            newlyAddedCollaborators = (0, _differenceWith2.default)(newCollaborators, oldCollaborators, _isEqual2.default);
            removedCollaborators = (0, _differenceWith2.default)(oldCollaborators, newCollaborators, _isEqual2.default);
            collaboratorPromises = [];
            newlyAddedCollaborators.forEach(function (collaborator) {
              collaboratorPromises.push(new UserCollectionCollaborator({
                collaboratorId: collaborator.id,
                collectionId: newCollection.get('id')
              }).save(null, {
                method: 'insert'
              }));
            });
            removedCollaborators.forEach(function (collaborator) {
              collaboratorPromises.push(new UserCollectionCollaborator({}).where('collection_id', newCollection.get('id')).where('collaborator_id', collaborator.id).destroy());
            });
            _context.next = 32;
            return Promise.all(collaboratorPromises);
          case 32:
            if (!(isNew || res.locals.collection.name !== newCollection.get('name'))) {
              _context.next = 36;
              break;
            }
            // Type needed for indexing
            newCollection.set('type', 'Collection');
            _context.next = 36;
            return search.indexEntity(newCollection);
          case 36:
            return _context.abrupt("return", res.status(200).send(newCollection.toJSON()));
          case 39:
            _context.prev = 39;
            _context.t0 = _context["catch"](0);
            return _context.abrupt("return", next(_context.t0));
          case 42:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 39]]);
  }));
  return _collectionCreateOrEditHandler.apply(this, arguments);
}
//# sourceMappingURL=collectionRouteUtils.js.map