-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathabstactModelFactory.ts
More file actions
72 lines (62 loc) · 1.95 KB
/
abstactModelFactory.ts
File metadata and controls
72 lines (62 loc) · 1.95 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Collection, Db, Document, ObjectId } from 'mongodb';
import AbstractModel, { ModelConstructor } from './abstractModel';
/**
* Model Factory class
*/
export default abstract class AbstractModelFactory<DBScheme extends Document, Model extends AbstractModel<DBScheme>> {
/**
* Database connection to interact with
*/
protected dbConnection: Db;
/**
* Model constructor to create instances
*/
private readonly Model: ModelConstructor<DBScheme, Model>;
/**
* Collection to work with
*/
protected abstract collection: Collection<DBScheme>;
/**
* Creates factory instance
* @param dbConnection - connection to DataBase
* @param model - model constructor
*/
protected constructor(dbConnection: Db, model: ModelConstructor<DBScheme, Model>) {
this.Model = model;
this.dbConnection = dbConnection;
}
/**
* Find record by query
* @param query - query object
*/
public async findOne(query: object): Promise<Model | null> {
const searchResult = await this.collection.findOne(query);
if (!searchResult) {
return null;
}
/**
* MongoDB returns WithId<DBScheme>, but Model constructor expects DBScheme.
* Since WithId<DBScheme> is DBScheme & { _id: ObjectId } and DBScheme already
* includes _id: ObjectId, they are structurally compatible.
*/
return new this.Model(searchResult as DBScheme);
}
/**
* Finds record by its id
* @param id - entity id
*/
public async findById(id: string): Promise<Model | null> {
const searchResult = await this.collection.findOne({
_id: new ObjectId(id),
} as any);
if (!searchResult) {
return null;
}
/**
* MongoDB returns WithId<DBScheme>, but Model constructor expects DBScheme.
* Since WithId<DBScheme> is DBScheme & { _id: ObjectId } and DBScheme already
* includes _id: ObjectId, they are structurally compatible.
*/
return new this.Model(searchResult as DBScheme);
}
}