47 lines
1.7 KiB
JavaScript
47 lines
1.7 KiB
JavaScript
const
|
|
Schema = require('mongoose').Schema,
|
|
Job = require('./job'),
|
|
User = require('./user'),
|
|
{ Fields, UserTypes } = require('../helpers/constants'),
|
|
mongoUtil = require('../helpers/mongo');
|
|
|
|
const schema = new Schema({
|
|
licence: { type: String, required: false }
|
|
}, { strictQuery: false });
|
|
|
|
async function updateRelatedJobs(session) {
|
|
session && (session.startTransaction(mongoUtil.getTranOps()));
|
|
try {
|
|
await Job.updateMany({ operator: this._id }, { $set: { operator: null } }).session(session);
|
|
} catch (error) {
|
|
session && (session.abortTransaction());
|
|
throw error;
|
|
}
|
|
await mongoUtil.commitWithRetry(session);
|
|
}
|
|
|
|
/**
|
|
* Remove the Pilot with all related data
|
|
* @param {ClientSession} ses the db session. If ses is null, create a session and end when done
|
|
* @param {boolean} markDeletedOnly Determine whether to just mark the item as deleted only. Default is true.
|
|
*/
|
|
schema.methods.removeFull = async function (ses = null, markDeletedOnly = true) {
|
|
const endSesDone = !ses;
|
|
const session = ses || await this.db.startSession({ readPreference: { mode: "primary" } });
|
|
try {
|
|
// 1. Mark this application and all its files as deleted - use transaction
|
|
if (!this[Fields.MARKED_DELETE])
|
|
await mongoUtil.runTransactionWithRetry(this.markAsDeleted.bind(this), session);
|
|
|
|
if (!markDeletedOnly) {
|
|
// 2. Set null for related jobs
|
|
await mongoUtil.runTransactionWithRetry(updateRelatedJobs.bind(this), session);
|
|
// 3. Delete the application
|
|
await mongoUtil.runTransactionWithRetry(this.deleteMarked.bind(this), session);
|
|
}
|
|
} finally {
|
|
if (endSesDone && session) await session.endSession();
|
|
}
|
|
}
|
|
|
|
module.exports = User.discriminator(UserTypes.PILOT, schema, { clone: false }); |