db.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import type { AccountModel } from './account/model'
  2. import type { Context } from './types'
  3. import type { HerdModel } from './herd/model'
  4. import { MongoClient } from 'mongodb'
  5. import type { TaskModel } from './task/model'
  6. import createAccountModel from './account/model'
  7. import createHerdModel from './herd/model'
  8. import createTaskModel from './task/model'
  9. /**
  10. * Models context.
  11. * Provides access to various backend functionality.
  12. */
  13. export interface Models {
  14. account: AccountModel
  15. herd: HerdModel
  16. task: TaskModel
  17. }
  18. /** Create a MongoDB connection and initialize models. */
  19. async function createDatabase(ctx: Context) {
  20. // Connect to MongoDB and select database
  21. const mongo = await MongoClient.connect(ctx.config.mongo.uri)
  22. const db = mongo.db(ctx.config.mongo.db)
  23. // Create a temporary context and set up models.
  24. // Some models may self-initialize to install indexes etc.
  25. const dbCtx = { ...ctx, mongo, db }
  26. const model = <Models>{
  27. account: await createAccountModel(dbCtx),
  28. herd: await createHerdModel(dbCtx),
  29. task: await createTaskModel(dbCtx),
  30. }
  31. return { mongo, db, model }
  32. }
  33. export default createDatabase