Add category.order to reorder siblings under a parent.
Sets each direct child's sort to its index in the given categoryIds, scoped by parentId. Validates the set matches the current children.
This commit is contained in:
62
src/store/category/order.js
Normal file
62
src/store/category/order.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
LIST_CHILD_IDS,
|
||||
UPDATE_SORT,
|
||||
} from '../../sql/category.js';
|
||||
import request from '../request.js';
|
||||
import resolveCategoryAccess from './resolveCategoryAccess.js';
|
||||
|
||||
export default function order(pool) {
|
||||
const access = resolveCategoryAccess(pool);
|
||||
|
||||
return async ({ googleAuthId, parentId, categoryIds }) => {
|
||||
if (!Array.isArray(categoryIds)) {
|
||||
throw new Error('Invalid category order');
|
||||
}
|
||||
|
||||
// Auth + ensures parentId is a real category of the user's company.
|
||||
await access(googleAuthId, parentId);
|
||||
|
||||
const children = await pool
|
||||
.request()
|
||||
.input('parentId', parentId)
|
||||
.query(LIST_CHILD_IDS);
|
||||
|
||||
const existing = new Set(children.recordset.map((r) => r.id));
|
||||
|
||||
if (categoryIds.length !== existing.size) {
|
||||
throw new Error('Invalid category order');
|
||||
}
|
||||
|
||||
const seen = new Set();
|
||||
for (const categoryId of categoryIds) {
|
||||
if (!Number.isFinite(categoryId) || !existing.has(categoryId) || seen.has(categoryId)) {
|
||||
throw new Error('Invalid category order');
|
||||
}
|
||||
seen.add(categoryId);
|
||||
}
|
||||
|
||||
const tx = pool.transaction();
|
||||
await tx.begin();
|
||||
|
||||
try {
|
||||
for (let sort = 0; sort < categoryIds.length; sort++) {
|
||||
await request(pool, tx)
|
||||
.input('id', categoryIds[sort])
|
||||
.input('parentId', parentId)
|
||||
.input('sort', sort)
|
||||
.query(UPDATE_SORT);
|
||||
}
|
||||
|
||||
await tx.commit();
|
||||
|
||||
return { categoryIds };
|
||||
} catch (err) {
|
||||
try {
|
||||
await tx.rollback();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user