Skip to content

Commit

Permalink
feat(mongo): add connection string support (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
arily authored Oct 23, 2020
1 parent f63b26a commit 3e2c728
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/plugin-mongo/src/database.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { MongoClient, Db, Collection } from 'mongodb'
import { App, TableType } from 'koishi-core'
import { URLSearchParams } from 'url'

export interface Config {
username?: string
password?: string
protocol?: string
host?: string
port?: number
/** database name */
name?: string
prefix?: string
/** default auth database */
authDatabase?: string
connectOptions?: ConstructorParameters<typeof URLSearchParams>[0]
/** connection string (will overwrite all configs except 'name' and 'prefix') */
uri?: string
}

export default class MongoDatabase {
Expand All @@ -24,9 +31,7 @@ export default class MongoDatabase {
}

async start() {
let mongourl = `${this.config.protocol}://`
if (this.config.username) mongourl += `${this.config.username}:${this.config.password}@`
mongourl += `${this.config.host}:${this.config.port}/${this.config.name}`
const mongourl = this.config.uri || this.connectionStringFromConfig()
this.client = await MongoClient.connect(
mongourl, { useNewUrlParser: true, useUnifiedTopology: true },
)
Expand All @@ -43,4 +48,16 @@ export default class MongoDatabase {
stop() {
return this.client.close()
}

connectionStringFromConfig() {
const { authDatabase, connectOptions, host, name, password, port, protocol, username } = this.config
let mongourl = `${protocol}://`
if (username) mongourl += `${username}${password ? `:${password}` : ''}@`
mongourl += `${host}${port ? `:${port}` : ''}/${authDatabase || name}`
if (connectOptions) {
const params = new URLSearchParams(connectOptions)
mongourl += `?${params}`
}
return mongourl
}
}

0 comments on commit 3e2c728

Please sign in to comment.