/*
* This file is part of PKM (Persistent Knowledge Monitor).
* Copyright (c) 2020 Capgemini Group, Commissariat à l'énergie atomique et aux énergies alternatives,
* OW2, Sysgo AG, Technikon, Tree Technology, Universitat Politècnica de València.
*
* PKM is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation.
*
* PKM 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with PKM. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Delete some documents in a generic manner from several collections of a database
*
* @memberof PKM
* @instance
* @param {string} dbName - database name
* @param {Array.<string>} collection_names - collection names
* @param {Object} [query] - query
* @param {Object} [options] - options
*
* @return {Promise} a promise
*/
function delete_documents_spanned(dbName, collection_names, query = {}, options = {})
{
return new Promise(function(resolve, reject)
{
// request for document deletion in each collections
Promise.allSettled(collection_names.map((collection_name) => this.delete_documents(dbName, collection_name, query, options))).then((promise_values) =>
{
// if there are no rejected promises
if(promise_values.find((promise_value) => promise_value.status === 'rejected') === undefined)
{
// then resolve
resolve();
}
else
{
// otherwise
const error = require('./error');
// if there are no failures, i.e. there are no rejected promises which are not 404 not found errors
const failure = promise_values.find((promise_value) => (promise_value.status === 'rejected') && !(promise_value.reason instanceof error.PKM_NotFound));
if(failure === undefined)
{
// then if there's a resolved promise (at least one of the others is a 404 not found error)
const found = promise_values.find((promise_value) => (promise_value.status === 'fulfilled'));
if(found !== undefined)
{
// then resolve
resolve();
}
else
{
// otherwise reject with Not found
reject(this.NotFound());
}
}
else
{
// otherwise, reject with the first failure
reject(failure.reason);
}
}
});
}.bind(this));
}
module.exports.delete_documents_spanned = delete_documents_spanned;