feat(SmartdataDoc): add custom unique indexes

This commit is contained in:
2018-07-10 21:27:16 +02:00
parent 1cf02157c4
commit 46514a2743
5 changed files with 562 additions and 1 deletions

View File

@ -31,6 +31,7 @@ export class SmartdataCollection<T> {
objectValidation: IDocValidationFunc<T> = null;
collectionName: string;
smartdataDb: SmartdataDb;
uniqueIndexes: string[] = [];
constructor(collectedClassArg: T & SmartDataDbDoc<T>, smartDataDbArg: SmartdataDb) {
// tell the collection where it belongs
@ -59,6 +60,21 @@ export class SmartdataCollection<T> {
}
}
/**
* mark unique index
*/
markUniqueIndexes(keyArrayArg: string[] = []) {
for(let key of keyArrayArg) {
if(!this.uniqueIndexes.includes(key)) {
this.mongoDbCollection.createIndex(key, {
unique: true
});
// make sure we only call this once and not for every doc we create
this.uniqueIndexes.push(key);
}
}
}
/**
* adds a validation function that all newly inserted and updated objects have to pass
*/
@ -81,6 +97,7 @@ export class SmartdataCollection<T> {
async insert(dbDocArg: T & SmartDataDbDoc<T>): Promise<any> {
await this.init();
await this.checkDoc(dbDocArg);
this.markUniqueIndexes(dbDocArg.uniqueIndexes);
const saveableObject = await dbDocArg.createSavableObject();
console.log(saveableObject);
const result = await this.mongoDbCollection.insertOne(saveableObject);

View File

@ -12,7 +12,7 @@ export type TDocCreation = 'db' | 'new' | 'mixed';
*/
export function svDb() {
return (target: SmartDataDbDoc<any>, key: string) => {
console.log('called sva');
console.log(`called svDb() on ${key}`);
if (!target.saveableProperties) {
target.saveableProperties = [];
}
@ -20,6 +20,27 @@ export function svDb() {
};
}
/**
* unique index - decorator to mark a unique index
*/
export function unI() {
return (target: SmartDataDbDoc<any>, key: string) => {
console.log('called unI');
// mark the index as unique
if (!target.uniqueIndexes) {
target.uniqueIndexes = [];
}
target.uniqueIndexes.push(key);
// and also save it
if (!target.saveableProperties) {
target.saveableProperties = [];
}
target.saveableProperties.push(key);
};
}
export class SmartDataDbDoc<T> {
/**
* the collection object an Doc belongs to
@ -31,6 +52,11 @@ export class SmartDataDbDoc<T> {
*/
creationStatus: TDocCreation = 'new';
/**
* unique indexes
*/
uniqueIndexes: string[];
/**
* an array of saveable properties of a doc
*/