Skip to content

Commit

Permalink
fix: index metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
Rmannn committed Apr 27, 2021
1 parent 7df6a60 commit 2e072ba
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/indexes/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { IndexSpecification } from 'mongodb';
import { setIndexMetadata } from './metadata';

export function Index(metadata?: Partial<IndexSpecification>) {
return (target: any, property: string) =>
return function (target: any, property: string) {
setIndexMetadata(
target,
property,
metadata === undefined ? {} : metadata
);
};
}
16 changes: 12 additions & 4 deletions src/indexes/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ export function setIndexMetadata(
) {
let targetMetadata: IndexMetadata[] | undefined = Reflect.getMetadata(
INDEX_METADATA_NAME,
target
target.constructor
);
if (targetMetadata === undefined) {
targetMetadata = [];
}

targetMetadata.push({ property, metadata });
Reflect.defineMetadata(
INDEX_METADATA_NAME,
Expand Down Expand Up @@ -53,7 +52,8 @@ export async function createIndexes<Model extends EntityInterface>(

// declared indexes
const indexesMetadata = getIndexMetadatas(ModelClass);
const collection = await manager.getCollection(ModelClass);
const collection = manager.getCollection(ModelClass);

if (indexesMetadata !== undefined) {
for (const index of indexesMetadata) {
const mongoIndex = {
Expand Down Expand Up @@ -90,6 +90,14 @@ export async function createIndexes<Model extends EntityInterface>(
}
}
if (indexes.length > 0) {
await collection.createIndexes(indexes);
try {
await collection.createIndexes(indexes);
} catch (e) {
throw new Error(
`Unable to create index on collection ${
collection.namespace
}: ${JSON.stringify(indexes)} ${e.message as string}`
);
}
}
}

0 comments on commit 2e072ba

Please sign in to comment.