Refactor stock event schema for improved ObjectId handling and error checking
All checks were successful
farmcontrol/farmcontrol-ws/pipeline/head This commit looks good

- Removed the unused `refId` import to streamline the code.
- Enhanced the `getStockEventTotal` function to validate `parentId` directly, improving error handling.
- Updated ObjectId creation logic to handle both string and ObjectId types, ensuring robustness in database queries.
- Added a mock implementation for the `use` method in socket manager tests to support middleware functionality.
This commit is contained in:
Tom Butcher 2026-11-07 19:17:28 +00:00
parent 1ae6c3f05c
commit 72c24ab700
2 changed files with 4 additions and 4 deletions

View File

@ -6,7 +6,6 @@ import {
aggregateRollups, aggregateRollups,
aggregateRollupsHistory, aggregateRollupsHistory,
} from '../../database.js'; } from '../../database.js';
import { refId } from '../../objectid.js';
const { Schema } = mongoose; const { Schema } = mongoose;
const parentStockModelNames = { const parentStockModelNames = {
@ -61,10 +60,10 @@ const buildParentState = (parentType, parentStock, currentAmount, startingAmount
}; };
const getStockEventTotal = async (parentId, parentType) => { const getStockEventTotal = async (parentId, parentType) => {
const id = refId(parentId); if (!parentId) return null;
if (typeof id !== 'string' || !/^[a-fA-F\d]{24}$/.test(id)) return null;
const objectId = new mongoose.Types.ObjectId(id); const objectId =
parentId instanceof mongoose.Types.ObjectId ? parentId : new mongoose.Types.ObjectId(parentId);
const [result] = await mongoose const [result] = await mongoose
.model('stockEvent') .model('stockEvent')

View File

@ -4,6 +4,7 @@ jest.unstable_mockModule('socket.io', () => ({
Server: jest.fn(() => ({ Server: jest.fn(() => ({
on: jest.fn(), on: jest.fn(),
emit: jest.fn(), emit: jest.fn(),
use: jest.fn(),
})), })),
})); }));