/*
* 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/>.
*/
/**
* Create collection
*
* @memberof PKM
* @instance
* @param {string} dbName - database name
* @param {string} collection_name - collection name
* @param {Object} [collection_info] - collection info
*
* @return {Promise} a promise
*/
function create_collection(dbName, collection_name, collection_info)
{
return new Promise(function(resolve, reject)
{
const db = this.client.db(dbName);
var collection_cursor = db.listCollections({ name : collection_name });
let count = 0;
collection_cursor.each((err, list_collections_result) =>
{
if(err)
{
reject(this.Error(err));
}
else if(list_collections_result)
{
++count;
}
else if(count)
{
reject(this.Conflict('Collection \'' + collection_name + '\' already exists in Database \'' + dbName + '\''));
}
else
{
db.createCollection(collection_name).then((collection) =>
{
if((collection_info === undefined) || (collection_info.index === undefined))
{
resolve(collection);
}
else
{
collection.createIndex(collection_info.index.key, collection_info.index.options).then(() =>
{
resolve(collection);
}).catch((err) =>
{
reject(this.Error(err));
});
}
}).catch((err) =>
{
reject(this.Error(err));
});
}
});
}.bind(this));
}
exports.create_collection = create_collection;