(config: MongoDBConnectionConfig)
| 6 | import type { MongoDBCollectionInfo, MongoDBConnectionConfig } from '@/tools/mongodb/types' |
| 7 | |
| 8 | export async function createMongoDBConnection(config: MongoDBConnectionConfig) { |
| 9 | const hostValidation = await validateDatabaseHost(config.host, 'host') |
| 10 | if (!hostValidation.isValid) { |
| 11 | throw new Error(hostValidation.error) |
| 12 | } |
| 13 | |
| 14 | const credentials = |
| 15 | config.username && config.password |
| 16 | ? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@` |
| 17 | : '' |
| 18 | |
| 19 | const queryParams = new URLSearchParams() |
| 20 | |
| 21 | if (config.authSource) { |
| 22 | queryParams.append('authSource', config.authSource) |
| 23 | } |
| 24 | |
| 25 | if (config.ssl === 'required') { |
| 26 | queryParams.append('ssl', 'true') |
| 27 | } |
| 28 | |
| 29 | const queryString = queryParams.toString() |
| 30 | const uri = `mongodb://${credentials}${config.host}:${config.port}/${config.database}${queryString ? `?${queryString}` : ''}` |
| 31 | |
| 32 | const client = new MongoClient(uri, { |
| 33 | connectTimeoutMS: 10000, |
| 34 | socketTimeoutMS: 10000, |
| 35 | maxPoolSize: 1, |
| 36 | lookup: createPinnedLookup(hostValidation.resolvedIP ?? config.host), |
| 37 | }) |
| 38 | |
| 39 | await client.connect() |
| 40 | return client |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Recursively checks an object for dangerous MongoDB operators |
no test coverage detected