Compare commits

..

4 Commits

Author SHA1 Message Date
f36d020bce
v1.5.9 2023-08-11 13:03:52 +03:00
e4e6fdf843
handle index mismatches properly 2023-08-11 13:03:38 +03:00
93d205eb37
v1.5.8 2023-08-11 12:06:13 +03:00
42b212273c
recreate index if exists when conflict occurs 2023-08-11 12:05:50 +03:00
2 changed files with 50 additions and 3 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@navy.gif/wrappers",
"version": "1.5.7",
"version": "1.5.9",
"description": "Various wrapper classes I use in my projects",
"repository": "https://git.corgi.wtf/Navy.gif/wrappers.git",
"author": "Navy.gif",

View File

@ -24,6 +24,20 @@ export type MongoOptions = {
load?: boolean
}
type StringIndexable = {[key: string]: boolean | string | number | Document | object}
const objIsSubset = (superObj: StringIndexable, subObj: StringIndexable): boolean =>
{
return Object.keys(subObj).every(ele =>
{
if (typeof subObj[ele] === 'object' && typeof superObj[ele] === 'object')
{
return objIsSubset(superObj[ele] as StringIndexable, subObj[ele] as StringIndexable);
}
return subObj[ele] === superObj[ele];
});
};
/**
* A dedicated class to locally wrap the mongodb API wrapper
*
@ -363,16 +377,25 @@ class MongoDB
return this.#db.collection(coll).countDocuments(query);
}
async ensureIndex (collection: string, index: IndexSpecification, options?: CreateIndexesOptions): Promise<void>
async ensureIndex (collection: string, index: IndexSpecification, options?: CreateIndexesOptions & StringIndexable): Promise<void>
{
if (!this.#db)
return Promise.reject(new Error('MongoDB not connected'));
if (!(index instanceof Array))
index = [ index ];
const indexes = await this.#db.collection(collection).indexes();
const existing = indexes.find(idx => idx.name.startsWith(index));
if (existing && this.#indexesEqual(existing, options))
return;
if (existing)
await this.#db.collection(collection).dropIndex(existing.name);
await this.#db.collection(collection).createIndex(index, options);
}
async ensureIndices (collection: string, indices: IndexSpecification[], options?: CreateIndexesOptions): Promise<void>
async ensureIndices (collection: string, indices: IndexSpecification[], options?: CreateIndexesOptions & StringIndexable): Promise<void>
{
if (!this.#db)
return Promise.reject(new Error('MongoDB not connected'));
@ -380,6 +403,30 @@ class MongoDB
await this.ensureIndex(collection, index, options);
}
#indexesEqual (existing: Document, options?: CreateIndexesOptions & StringIndexable)
{
// 3 keys on the existing means that only the name was given
if (!options && Object.keys(existing).length === 3)
return true;
else if (!options)
return false;
const keys = Object.keys(options);
for (const key of keys)
{
if (typeof options[key] !== typeof existing[key])
return false;
if (typeof options[key] === 'object' && !objIsSubset(existing, options))
return false;
else if (options[key] !== existing[key])
return false;
}
return true;
}
}
export { MongoDB };