import * as Mongo from "mongodb" import { Collection } from "./Collection" import { Document } from "./Document" export class Connection { private client: Promise private readonly database: Promise protected constructor(url: Promise, database?: Promise) { this.client = url.then(u => Mongo.MongoClient.connect(u).catch(() => undefined)) this.database = this.client .then(async c => (c ? c.db(database ? await database : undefined) : undefined)) .catch(() => undefined) } async get( name: string, shard: Shard, idLength: 4 | 8 | 12 | 16 = 16 ): Promise | undefined> { const database = await this.database return database ? new Collection(database.collection(name), shard, idLength) : undefined } async close(): Promise { const client = await this.client if (client) await client.close() } static open(url: string, database?: string): Connection { return new Connection(Promise.resolve(url), database ? Promise.resolve(database) : undefined) } }