Tom Butcher f3a3d3914a
All checks were successful
farmcontrol/farmcontrol-ws/pipeline/head This commit looks good
Enhance gcode file schema to populate part information from partSku
- Added logic in the pre-validation hook to populate the `part` field in `parts` array based on the `partSku` if it is not already set.
- Improved data integrity by ensuring that part information is correctly retrieved and assigned during validation.
2026-07-26 21:21:35 +01:00

50 lines
1.7 KiB
JavaScript

import mongoose from 'mongoose';
import { generateId } from '../../utils.js';
const { Schema } = mongoose;
const partSchema = new mongoose.Schema({
part: { type: Schema.Types.ObjectId, ref: 'part', required: true },
partSku: { type: Schema.Types.ObjectId, ref: 'partSku', required: true },
quantity: { type: Number, required: true },
});
const gcodeFileSchema = new mongoose.Schema(
{
_reference: { type: String, default: () => generateId()() },
name: { required: true, type: String },
gcodeFileName: { required: false, type: String },
size: { type: Number, required: false },
filament: { type: Schema.Types.ObjectId, ref: 'filament', required: true },
filamentSku: { type: Schema.Types.ObjectId, ref: 'filamentSku', required: true },
parts: [partSchema],
file: { type: mongoose.SchemaTypes.ObjectId, ref: 'file', required: false },
cost: { type: Number, required: false },
},
{ timestamps: true }
);
gcodeFileSchema.pre('validate', async function () {
if (!this.filament && this.filamentSku) {
const sku = await mongoose.model('filamentSku').findById(this.filamentSku).select('filament').lean();
if (sku?.filament) this.filament = sku.filament;
}
if (this.parts?.length) {
for (const partItem of this.parts) {
if (!partItem.part && partItem.partSku) {
const sku = await mongoose.model('partSku').findById(partItem.partSku).select('part').lean();
if (sku?.part) partItem.part = sku.part;
}
}
}
});
gcodeFileSchema.index({ name: 'text', gcodeFileName: 'text' });
gcodeFileSchema.virtual('id').get(function () {
return this._id;
});
gcodeFileSchema.set('toJSON', { virtuals: true });
export const gcodeFileModel = mongoose.model('gcodeFile', gcodeFileSchema);