Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { MongoClient, Db } from 'mongodb';
- interface Connection {
- uri: string;
- databaseName: string;
- }
- interface Connect {
- db: Db;
- connection: Connection;
- connectToDatabase(): Promise<this>;
- }
- export class MongoConnect implements Connect {
- public db!: Db;
- readonly connection: Connection;
- constructor(connect: Connection) {
- this.connection = connect;
- }
- async connectToDatabase() {
- const { uri, databaseName } = this.connection;
- const client: MongoClient = new MongoClient(
- uri, { useNewUrlParser: true }
- );
- try {
- await client.connect();
- this.db = await client.db(databaseName)
- console.log(`[Mongo] Connected to ${ databaseName }`);
- return this;
- }
- catch (error) {
- throw new Error(error);
- }
- }
- }
- // in index.ts
- // imports etc.
- (async (): Promise<void> => {
- // ...
- const mongo: MongoConnect = await new MongoConnect({
- uri: URI,
- databaseName: 'test',
- }).connectToDatabase();
- const application = await app({ database: mongo });
- // ...
- })();
- // in app.ts
- // imports etc.
- interface App {
- database: MongoConnect;
- }
- export default async ({ database }: App): Promise<express.Application> => {
- const app: express.Application = express();
- app.use(
- routes(
- methods(database.db.collection(TYPES.collectionName))
- )
- );
- return app;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement