-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovider.mongodb.ts
95 lines (82 loc) · 2.54 KB
/
provider.mongodb.ts
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
import { Collection, Db, MongoClient, ObjectID } from 'mongodb';
import { environment } from './environment';
export class MongoDbProvider {
private database?: Db;
private mongoClient: MongoClient;
constructor(url: string) {
this.mongoClient = new MongoClient(url) // , { useUnifiedTopology: true });
}
get validatorsCollection(): Collection {
const validatorsCollection = this.getCollection('w3f_validator');
if (!validatorsCollection) {
throw new Error('Validator collection is undefined');
}
return validatorsCollection;
}
get postsCollection(): Collection {
const postsCollection = this.getCollection('posts');
if (!postsCollection) {
throw new Error('Posts collection is undefined');
}
return postsCollection;
}
get usersCollection(): Collection {
const usersCollection = this.getCollection('users');
if (!usersCollection) {
throw new Error('Users collection is undefined');
}
return usersCollection;
}
/**
* Connect to MongoDB.
* @async
* @param databaseName - Database name.
*/
async connectAsync(databaseName: string): Promise<void> {
await this.mongoClient.connect();
this.database = this.mongoClient.db(databaseName);
}
/**
* Close the database and its underlying connections.
*/
async closeAsync(): Promise<void> {
await this.mongoClient.close();
}
/**
* Fetch a specific collection.
* @private
* @param collectionName - Collection name.
* @returns The collection instance.
*/
private getCollection(collectionName: string): Collection {
if (!this.database) {
throw new Error('Database is undefined.');
}
return this.database.collection(collectionName);
}
}
export const mongoDbProvider = new MongoDbProvider(environment.mongoDb.url);
/**
* Add mock users if `users` collection is empty.
* TODO: Remove in Production.
*/
// export async function addMockUsersAsync(): Promise<void> {
// const usersCount = await mongoDbProvider.usersCollection.countDocuments();
// if (usersCount === 0) {
// await mongoDbProvider.usersCollection.insertMany([
// {
// _id: new ObjectID('0123456789abcdef01234567'),
// firstName: 'Test',
// lastName: 'User 1',
// email: '[email protected]',
// },
// {
// _id: new ObjectID('fedcba987654321098765432'),
// firstName: 'Test',
// lastName: 'User 2',
// email: '[email protected]',
// following: [new ObjectID('0123456789abcdef01234567')],
// },
// ]);
// }
// }