Enhanced database functions with pagination support in listObjects, added checkStates function for state validation, and introduced editObjects function for batch updates. Updated editObject to include recalculate parameter.

This commit is contained in:
Tom Butcher 2025-12-27 13:57:43 +00:00
parent 85f9ca8b6d
commit 9ab08f39a1

View File

@ -349,12 +349,14 @@ export const listObjects = async ({
filter = {}, filter = {},
sort = '', sort = '',
order = 'ascend', order = 'ascend',
pagination = true,
project, // optional: override default projection project, // optional: override default projection
}) => { }) => {
try { try {
logger.trace('Listing object:', { logger.trace('Listing object:', {
model, model,
populate, populate,
pagination,
page, page,
limit, limit,
filter, filter,
@ -363,7 +365,7 @@ export const listObjects = async ({
project, project,
}); });
// Calculate the skip value based on the page number and limit // Calculate the skip value based on the page number and limit
const skip = (page - 1) * limit; const skip = pagination ? (page - 1) * limit : 0;
// Fix: descend should be -1, ascend should be 1 // Fix: descend should be -1, ascend should be 1
const sortOrder = order === 'descend' ? -1 : 1; const sortOrder = order === 'descend' ? -1 : 1;
@ -389,7 +391,7 @@ export const listObjects = async ({
.find(filter) .find(filter)
.sort({ [sort]: sortOrder }) .sort({ [sort]: sortOrder })
.skip(skip) .skip(skip)
.limit(Number(limit)); .limit(pagination ? Number(limit) : undefined);
// Handle populate (array or single value) // Handle populate (array or single value)
if (populate) { if (populate) {
@ -599,7 +601,7 @@ export const listObjectsByProperties = async ({
} else { } else {
// If no properties specified, just return all objects without grouping // If no properties specified, just return all objects without grouping
// Ensure pipeline is not empty by adding a $match stage if needed // Ensure pipeline is not empty by adding a $match stage if needed
if (pipeline.length === 0) { if (pipeline.length === 0 && masterFilter == {}) {
pipeline.push({ $match: {} }); pipeline.push({ $match: {} });
} }
const results = await model.aggregate(pipeline); const results = await model.aggregate(pipeline);
@ -731,8 +733,25 @@ export const listObjectDependencies = async ({ model, id }) => {
} }
}; };
export const checkStates = async ({ model, id, states }) => {
try {
const object = await getObject({ model, id, cached: true });
if (!object?.state?.type) {
logger.warn(`Object ${id} has no state type.`);
return false;
}
if (states.includes(object?.state?.type)) {
return true;
}
return false;
} catch (error) {
logger.error('checkStates error:', error);
return { error: error.message, code: 500 };
}
};
// Reusable function to edit an object by ID, with audit logging and distribution // Reusable function to edit an object by ID, with audit logging and distribution
export const editObject = async ({ model, id, updateData, user, populate }) => { export const editObject = async ({ model, id, updateData, user, populate, recalculate = true }) => {
try { try {
// Determine parentType from model name // Determine parentType from model name
const parentType = model.modelName ? model.modelName : 'unknown'; const parentType = model.modelName ? model.modelName : 'unknown';
@ -810,7 +829,7 @@ export const editObject = async ({ model, id, updateData, user, populate }) => {
populate, populate,
}); });
if (model.recalculate) { if (model.recalculate && recalculate == true) {
logger.debug(`Recalculating ${model.modelName}`); logger.debug(`Recalculating ${model.modelName}`);
await model.recalculate(updatedObject, user); await model.recalculate(updatedObject, user);
} }
@ -828,6 +847,33 @@ export const editObject = async ({ model, id, updateData, user, populate }) => {
} }
}; };
// Reusable function to edit multiple objects
export const editObjects = async ({ model, updates, user, populate, recalculate = true }) => {
try {
const results = [];
for (const update of updates) {
const id = update._id || update.id;
const updateData = { ...update };
delete updateData._id;
delete updateData.id;
const result = await editObject({
model,
id,
updateData,
user,
populate,
recalculate,
});
results.push(result);
}
return results;
} catch (error) {
logger.error('editObjects error:', error);
return { error: error.message, code: 500 };
}
};
// Reusable function to create a new object // Reusable function to create a new object
export const newObject = async ({ model, newData, user = null }, distributeChanges = true) => { export const newObject = async ({ model, newData, user = null }, distributeChanges = true) => {
try { try {