Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import { MongoClient, Db } from 'mongodb';
  2.  
  3. interface Connection {
  4. uri: string;
  5. databaseName: string;
  6. }
  7.  
  8. interface Connect {
  9. db: Db;
  10. connection: Connection;
  11. connectToDatabase(): Promise<this>;
  12. }
  13.  
  14. export class MongoConnect implements Connect {
  15. public db!: Db;
  16. readonly connection: Connection;
  17.  
  18. constructor(connect: Connection) {
  19. this.connection = connect;
  20. }
  21.  
  22. async connectToDatabase() {
  23. const { uri, databaseName } = this.connection;
  24.  
  25. const client: MongoClient = new MongoClient(
  26. uri, { useNewUrlParser: true }
  27. );
  28.  
  29. try {
  30. await client.connect();
  31. this.db = await client.db(databaseName)
  32. console.log(`[Mongo] Connected to ${ databaseName }`);
  33.  
  34. return this;
  35. }
  36. catch (error) {
  37. throw new Error(error);
  38. }
  39. }
  40. }
  41.  
  42. // in index.ts
  43.  
  44. // imports etc.
  45.  
  46. (async (): Promise<void> => {
  47. // ...
  48.  
  49. const mongo: MongoConnect = await new MongoConnect({
  50. uri: URI,
  51. databaseName: 'test',
  52. }).connectToDatabase();
  53.  
  54. const application = await app({ database: mongo });
  55.  
  56. // ...
  57. })();
  58.  
  59. // in app.ts
  60.  
  61. // imports etc.
  62.  
  63. interface App {
  64. database: MongoConnect;
  65. }
  66.  
  67. export default async ({ database }: App): Promise<express.Application> => {
  68. const app: express.Application = express();
  69.  
  70. app.use(
  71. routes(
  72. methods(database.db.collection(TYPES.collectionName))
  73. )
  74. );
  75.  
  76. return app;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement