Files
dashlibstorage/src/store/attributename/order.js
2026-09-29 16:16:05 +02:00

69 lines
2.3 KiB
JavaScript

import {
LIST_IDS_BY_COMPANY as MSSQL_LIST_IDS,
UPDATE_SORT as MSSQL_UPDATE_SORT,
} from '../../providers/mssql/queries/attributename.js';
import {
LIST_IDS_BY_COMPANY as SQLITE_LIST_IDS,
UPDATE_SORT as SQLITE_UPDATE_SORT,
} from '../../providers/sqlite3/queries/attributename.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export default function order(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const listIdsSql = isSqlite ? SQLITE_LIST_IDS : MSSQL_LIST_IDS;
const updateSortSql = isSqlite ? SQLITE_UPDATE_SORT : MSSQL_UPDATE_SORT;
/**
* Reorders the attribute names for the user's selected company.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Reorder input.
* @param {Array<number>} input.attributenameIds - IDs in their new order.
* @param {object} [tx] - Optional transaction.
* @returns {Promise<{attributenameIds: Array<number>}>}
*/
return async (googleAuthId, { attributenameIds } = {}, tx) => {
if (!Array.isArray(attributenameIds)) {
throw new Error('Invalid attribute name order');
}
const runOrder = async (runner) => {
const { companyId } = await access(googleAuthId, runner);
const existingRows = await runner.query(listIdsSql, { companyId });
const existing = new Set(existingRows.rows.map((r) => r.id));
if (attributenameIds.length !== existing.size) {
throw new Error('Invalid attribute name order');
}
const seen = new Set();
for (const id of attributenameIds) {
if (!Number.isFinite(id) || !existing.has(id) || seen.has(id)) {
throw new Error('Invalid attribute name order');
}
seen.add(id);
}
for (let sort = 0; sort < attributenameIds.length; sort++) {
await runner.query(updateSortSql, {
id: attributenameIds[sort],
companyId,
sort,
});
}
return { attributenameIds };
};
if (tx) {
return runOrder(makeRunner(provider, tx));
}
if (typeof provider?.transaction === 'function') {
return provider.transaction(runOrder);
}
return runOrder(makeRunner(provider));
};
}