-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathdatabase.ts
More file actions
executable file
·165 lines (129 loc) · 3.84 KB
/
database.ts
File metadata and controls
executable file
·165 lines (129 loc) · 3.84 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import { EventEmitter } from 'events';
import {
MongoClient,
MongoClientOptions, Db,
CollectionOptions,
CreateCollectionOptions,
Collection,
MongoError,
Document, ClientSession, TransactionOptions,
} from 'mongodb';
import { IDatabase, IDocument, ServiceOptions } from './types';
import Service from './service';
import logger from './utils/logger';
import OutboxService from './events/outbox';
// add the ability to pass transaction options
const transactionOptions: TransactionOptions = {
readConcern: { level: 'local' },
writeConcern: { w: 1 },
};
class Database extends EventEmitter {
url: string;
dbName?: string;
options: MongoClientOptions;
private db?: Db;
connectPromise: Promise<void>;
connectPromiseResolve?: (value: void) => void;
outboxService: OutboxService;
private client?: MongoClient;
constructor(url: string, dbName?: string, options: MongoClientOptions = {}) {
super();
this.url = url;
this.dbName = dbName;
this.options = options;
this.connectPromise = new Promise((res) => { this.connectPromiseResolve = res; });
this.outboxService = new OutboxService(this.getOrCreateCollection, this.waitForConnection);
this.db = undefined;
}
public waitForConnection = async (): Promise<void> => {
await this.connectPromise;
};
public getOutboxService = (): OutboxService => this.outboxService;
connect = async (): Promise<void> => {
try {
this.client = await MongoClient.connect(this.url, this.options);
this.db = this.client.db(this.dbName);
this.emit('connected');
logger.info('Connected to mongodb.');
this.client.on('close', this.onClose);
if (this.connectPromiseResolve) {
this.connectPromiseResolve();
}
} catch (e) {
this.emit('error', e);
}
};
close = async (): Promise<void> => {
if (!this.client) {
return;
}
logger.info('Disconnecting from mongodb.');
await this.client.close();
};
createService<T extends IDocument>(
collectionName: string,
options?: ServiceOptions<T> | undefined,
): Service<T> {
return new Service<T>(
collectionName,
this as IDatabase,
options,
);
}
async ping(): Promise<any> {
await this.waitForConnection();
if (!this.db) {
return null;
}
return this.db.command({ ping: 1 });
}
private onClose(error: any) {
this.emit('disconnected', error);
}
public getOrCreateCollection = async <T extends Document>(
name: string,
opt: {
collectionCreateOptions?: CreateCollectionOptions;
collectionOptions?: CollectionOptions;
} = {},
): Promise<Collection<T>> => {
await this.waitForConnection();
if (!this.db) {
throw new Error('The db object is not defined');
}
try {
await this.db.createCollection<T>(name, opt.collectionCreateOptions || {});
} catch (error) {
if (error instanceof MongoError && error.code === 48) {
return this.db.collection<T>(name, opt.collectionOptions || {});
}
throw error;
}
return this.db.collection<T>(name, opt.collectionOptions || {});
};
public getClient = async (): Promise<MongoClient | undefined> => {
await this.connectPromise;
return this.client;
};
public withTransaction = async <TRes = any>(
transactionFn: (session: ClientSession) => Promise<TRes>,
): Promise<TRes> => {
if (!this.client) {
throw new Error('MongoDB client is not connected');
}
const session = this.client.startSession();
let res: any;
try {
await session.withTransaction(async () => {
res = await transactionFn(session);
}, transactionOptions);
} catch (error: any) {
logger.error(error.stack || error);
throw error;
} finally {
await session.endSession();
}
return res as TRes;
};
}
export default Database;