forked from finos/git-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.ts
More file actions
73 lines (62 loc) · 2.28 KB
/
helper.ts
File metadata and controls
73 lines (62 loc) · 2.28 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
import { MongoClient, Db, Collection, Filter, Document, FindOptions } from 'mongodb';
import { getDatabase } from '../../config';
import MongoDBStore from 'connect-mongo';
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
let _db: Db | null = null;
let _client: MongoClient | null = null;
// Reset connection - useful for testing
export const resetConnection = async (): Promise<void> => {
if (_client) {
await _client.close();
_client = null;
_db = null;
}
};
// Get the database instance - useful for testing
export const getDb = (): Db | null => _db;
export const connect = async (collectionName: string): Promise<Collection> => {
//retrieve config at point of use (rather than import)
const dbConfig = getDatabase();
const connectionString = dbConfig.connectionString;
const options = dbConfig.options;
if (!_db) {
if (!connectionString) {
throw new Error('MongoDB connection string is not provided');
}
if (options?.authMechanismProperties?.AWS_CREDENTIAL_PROVIDER) {
// we break from the config types here as we're providing a function to the mongoDB client
(options.authMechanismProperties.AWS_CREDENTIAL_PROVIDER as any) = fromNodeProviderChain();
}
_client = new MongoClient(connectionString, options);
await _client.connect();
_db = _client.db();
}
return _db.collection(collectionName);
};
export const findDocuments = async <T>(
collectionName: string,
filter: Filter<Document> = {},
options: FindOptions<Document> = {},
): Promise<T[]> => {
const collection = await connect(collectionName);
return collection.find(filter, options).toArray() as Promise<T[]>;
};
export const findOneDocument = async <T>(
collectionName: string,
filter: Filter<Document> = {},
options: FindOptions<Document> = {},
): Promise<T | null> => {
const collection = await connect(collectionName);
return (await collection.findOne(filter, options)) as T | null;
};
export const getSessionStore = () => {
//retrieve config at point of use (rather than import)
const dbConfig = getDatabase();
const connectionString = dbConfig.connectionString;
const options = dbConfig.options;
return new MongoDBStore({
mongoUrl: connectionString,
collectionName: 'user_session',
mongoOptions: options,
});
};