server/helpers/collectionRouteUtils.js

"use strict";

require("core-js/modules/es.object.get-own-property-descriptor.js");
require("core-js/modules/es.weak-map.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
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.array.iterator.js");
require("core-js/modules/es.date.to-json.js");
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.promise.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/web.dom-collections.for-each.js");
require("core-js/modules/web.dom-collections.iterator.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 cache;
function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var r, c, a = Object.defineProperty, n = { __proto__: null, default: e }; if (Object(e) !== e) return n; if (cache || "function" != typeof WeakMap || (cache = new WeakMap()), cache) { if (cache.has(e)) return cache.get(e); cache.set(e, n); } for (c in e) "default" !== c && {}.hasOwnProperty.call(e, c) && ((r = a && Object.getOwnPropertyDescriptor(e, c)) && (r.get || r.set) ? a(n, c, r) : n[c] = e[c]); return n; }
/*
 * 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, oldCollaborators, newCollaborators, newlyAddedCollaborators, removedCollaborators, collaboratorPromises, _t;
    return _regenerator.default.wrap(function (_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 = 2;
            break;
          }
          _context.next = 1;
          return new UserCollection({
            ownerId: req.user.id
          });
        case 1:
          newCollection = _context.sent;
          method = 'insert';
          _context.next = 5;
          break;
        case 2:
          if (!((_res$locals$collectio = res.locals.collection) !== null && _res$locals$collectio !== void 0 && (_res$locals$collectio = _res$locals$collectio.items) !== null && _res$locals$collectio !== void 0 && _res$locals$collectio.length && (0, _upperFirst2.default)((0, _camelCase2.default)(req.body.entityType)) !== res.locals.collection.entityType)) {
            _context.next = 3;
            break;
          }
          throw new _error.BadRequestError('Trying to change entityType of a non empty collection');
        case 3:
          _context.next = 4;
          return new UserCollection({
            id: req.params.collectionId
          }).fetch({
            require: true
          });
        case 4:
          newCollection = _context.sent;
          method = 'update';
          newCollection.set('last_modified', new Date());
        case 5:
          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 = 6;
          return newCollection.save(null, {
            method: method
          });
        case 6:
          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 = 7;
          return Promise.all(collaboratorPromises);
        case 7:
          if (!(isNew || res.locals.collection.name !== newCollection.get('name'))) {
            _context.next = 8;
            break;
          }
          // Type needed for indexing
          newCollection.set('type', 'Collection');
          _context.next = 8;
          return search.indexEntity(newCollection);
        case 8:
          return _context.abrupt("return", res.status(200).send(newCollection.toJSON()));
        case 9:
          _context.prev = 9;
          _t = _context["catch"](0);
          return _context.abrupt("return", next(_t));
        case 10:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[0, 9]]);
  }));
  return _collectionCreateOrEditHandler.apply(this, arguments);
}
//# sourceMappingURL=collectionRouteUtils.js.map