-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathabstractModel.ts
More file actions
47 lines (42 loc) · 1.45 KB
/
abstractModel.ts
File metadata and controls
47 lines (42 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Collection, Db, Document } from 'mongodb';
import { databases } from '../mongo';
/**
* Model constructor type
*/
export type ModelConstructor<DBScheme extends Document, Model extends AbstractModel<DBScheme>> = new (modelData: DBScheme) => Model;
/**
* Base model
*/
export default abstract class AbstractModel<DBScheme extends Document> {
/**
* Database connection to interact with DB
*/
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
protected readonly dbConnection: Db = databases.hawk!;
/**
* Model's collection
*/
protected abstract collection: Collection<DBScheme>;
/**
* Creates model instance
* @param modelData - data to fill model
*/
protected constructor(modelData: DBScheme) {
Object.assign(this, modelData);
};
/**
* Update entity data
* @param query - query to match
* @param data - update data (supports MongoDB dot notation for nested fields)
* @return number of documents modified
*/
public async update(query: object, data: Partial<DBScheme> | Record<string, any>): Promise<number> {
/**
* Type assertion is needed because MongoDB's updateOne accepts both
* Partial<DBScheme> (for regular updates) and Record<string, any>
* (for dot notation like 'identities.workspaceId.saml.id'), but the
* type system requires MatchKeysAndValues<DBScheme>.
*/
return (await this.collection.updateOne(query, { $set: data as any })).modifiedCount;
}
}