|
@@ -1,5 +1,6 @@
|
|
|
import type { Context } from '../types'
|
|
|
import { ObjectId } from 'mongodb'
|
|
|
+import type { Task } from '../task/types'
|
|
|
import type { Herd, HerdCreate, HerdUpdate } from './types'
|
|
|
|
|
|
/** Model for accessing and managing herds. */
|
|
@@ -8,6 +9,7 @@ export type HerdModel = Awaited<ReturnType<typeof createHerdModel>>
|
|
|
/** Create a herd model. */
|
|
|
async function createHerdModel(ctx: Context) {
|
|
|
const collection = ctx.db.collection<Herd>('herd')
|
|
|
+ const taskCollection = ctx.db.collection<Task>('task')
|
|
|
|
|
|
/** Create a herd. */
|
|
|
async function create(input: HerdCreate) {
|
|
@@ -29,6 +31,45 @@ async function createHerdModel(ctx: Context) {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * Delete a herd.
|
|
|
+ * This function removes all tasks associated with the herd and returns the number of tasks deleted.
|
|
|
+ */
|
|
|
+ async function _delete(id: ObjectId) {
|
|
|
+ if (ctx.config.mongo.useTransactions) return _deleteTx(id)
|
|
|
+
|
|
|
+ // Delete tasks
|
|
|
+ const { deletedCount } = await taskCollection.deleteMany({ _herd: id })
|
|
|
+
|
|
|
+ // Delete herd
|
|
|
+ await collection.deleteOne({ _id: id })
|
|
|
+
|
|
|
+ return deletedCount
|
|
|
+ }
|
|
|
+
|
|
|
+ /** Delete a herd using a transaction. */
|
|
|
+ async function _deleteTx(id: ObjectId) {
|
|
|
+ const session = ctx.mongo.startSession()
|
|
|
+ try {
|
|
|
+ session.startTransaction()
|
|
|
+
|
|
|
+ // Delete tasks
|
|
|
+ const { deletedCount } = await taskCollection.deleteMany({ _herd: id }, { session })
|
|
|
+
|
|
|
+ // Delete herd
|
|
|
+ await collection.deleteOne({ _id: id })
|
|
|
+
|
|
|
+ // Commit and return
|
|
|
+ await session.commitTransaction()
|
|
|
+ return deletedCount
|
|
|
+ } catch (err) {
|
|
|
+ await session.abortTransaction()
|
|
|
+ throw err
|
|
|
+ } finally {
|
|
|
+ await session.endSession()
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* Update a herd.
|
|
|
*/
|
|
@@ -49,6 +90,7 @@ async function createHerdModel(ctx: Context) {
|
|
|
return {
|
|
|
collection,
|
|
|
create,
|
|
|
+ delete: _delete,
|
|
|
init,
|
|
|
update,
|
|
|
}
|