mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
"use strict";
|
|
|
|
/**
|
|
* For CREATE — plain text array, no IDs needed
|
|
* objectives: ["text1"] or [{ text: "text1" }]
|
|
*/
|
|
async function syncObjectivesCreate(Model, parentField, parentId, objectives, transaction) {
|
|
if (!objectives?.length) return;
|
|
|
|
await Model.bulkCreate(
|
|
objectives.map((o, i) => ({
|
|
[parentField]: parentId,
|
|
text: typeof o === "string" ? o : o.text,
|
|
order_index: i,
|
|
})),
|
|
{ transaction }
|
|
);
|
|
}
|
|
|
|
/**
|
|
* For UPDATE — upsert by PK field (default "objective_id"), hard delete removed ones
|
|
* objectives: [{ objective_id: "123", text: "text1" }, { text: "new" }]
|
|
*/
|
|
async function syncObjectivesUpdate(Model, parentField, parentId, objectives, transaction, pkField = "objective_id") {
|
|
if (!objectives?.length) {
|
|
await Model.destroy({ where: { [parentField]: parentId }, force: true, transaction });
|
|
return;
|
|
}
|
|
|
|
const existing = await Model.findAll({ where: { [parentField]: parentId }, transaction });
|
|
const existingMap = new Map(existing.map((o) => [String(o[pkField]), o]));
|
|
const incomingIds = new Set(
|
|
objectives.filter((o) => o[pkField]).map((o) => String(o[pkField]))
|
|
);
|
|
|
|
// Hard delete removed
|
|
const toDelete = existing.filter((o) => !incomingIds.has(String(o[pkField])));
|
|
if (toDelete.length) {
|
|
await Model.destroy({
|
|
where: { [pkField]: toDelete.map((o) => o[pkField]) },
|
|
force: true,
|
|
transaction,
|
|
});
|
|
}
|
|
|
|
// Update existing or create new
|
|
for (let i = 0; i < objectives.length; i++) {
|
|
const item = objectives[i];
|
|
const record = item[pkField] ? existingMap.get(String(item[pkField])) : null;
|
|
|
|
if (record) {
|
|
await record.update({ text: item.text, order_index: i }, { transaction });
|
|
} else {
|
|
await Model.create(
|
|
{ [parentField]: parentId, text: item.text, order_index: i },
|
|
{ transaction }
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = { syncObjectivesCreate, syncObjectivesUpdate }; |