model.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import type { Context } from '../types'
  2. import { ObjectId } from 'mongodb'
  3. import type { Task, TaskCreate, TaskUpdate } from './types'
  4. /** Model for accessing and managing tasks. */
  5. export type TaskModel = Awaited<ReturnType<typeof createTaskModel>>
  6. /** Create a task model. */
  7. async function createTaskModel(ctx: Context) {
  8. const collection = ctx.db.collection<Task>('task')
  9. /** Create a task. */
  10. async function create(input: TaskCreate) {
  11. const result = await collection.insertOne({
  12. _herd: input._herd,
  13. _account: input._account,
  14. description: input.description,
  15. position: input.position,
  16. })
  17. return await collection.findOne({ _id: result.insertedId })
  18. }
  19. /** Initialize the task collection. */
  20. async function init() {
  21. await ctx.db.createCollection('task')
  22. }
  23. /**
  24. * Update a task.
  25. */
  26. async function update(id: ObjectId | string, input: TaskUpdate) {
  27. const changes = <Partial<Task>>{}
  28. if (input._herd) changes._herd = input._herd
  29. if (input._account) changes._account = input._account
  30. if (input.description) changes.description = input.description
  31. if (input.position !== undefined) changes.position = input.position
  32. return collection.findOneAndUpdate(
  33. { _id: new ObjectId(id) },
  34. { $set: changes },
  35. { returnDocument: 'after' },
  36. )
  37. }
  38. // Initialize on startup
  39. await init()
  40. return {
  41. collection,
  42. create,
  43. init,
  44. update,
  45. }
  46. }
  47. export default createTaskModel