73 lines
2.4 KiB
JavaScript
73 lines
2.4 KiB
JavaScript
import {
|
|
GET_BY_COMPANY_AND_ID as MSSQL_GET,
|
|
UPDATE_BY_ID as MSSQL_UPDATE,
|
|
} from '../../providers/mssql/queries/attributename.js';
|
|
import {
|
|
GET_BY_COMPANY_AND_ID as SQLITE_GET,
|
|
UPDATE_BY_ID as SQLITE_UPDATE,
|
|
} from '../../providers/sqlite3/queries/attributename.js';
|
|
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
|
import makeRunner from '../runner.js';
|
|
|
|
function parseValues(raw) {
|
|
if (!raw) return [];
|
|
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
return Array.isArray(parsed) ? parsed : [];
|
|
}
|
|
|
|
export default function update(provider) {
|
|
const access = resolveSelectedCompanyAccess(provider);
|
|
const isSqlite = provider?.dialect === 'sqlite3';
|
|
const getSql = isSqlite ? SQLITE_GET : MSSQL_GET;
|
|
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
|
|
|
|
/**
|
|
* Updates an attribute name for the user's selected company.
|
|
*
|
|
* @param {number} googleAuthId - The id of the Google auth user.
|
|
* @param {number} id - The attribute name id.
|
|
* @param {object} input - Update patch.
|
|
* @param {string} [input.name] - New name.
|
|
* @param {number} [input.sort] - New sort.
|
|
* @param {boolean} [input.exclusive] - New exclusive flag.
|
|
* @param {object} [tx] - Optional transaction.
|
|
* @returns {Promise<{id: number, name: string, sort: number, exclusive: boolean, values: Array}>}
|
|
*/
|
|
return async (googleAuthId, id, input = {}, tx) => {
|
|
if (!id || !Number.isInteger(Number(id))) {
|
|
throw new Error('Invalid id');
|
|
}
|
|
|
|
const runner = makeRunner(provider, tx);
|
|
const { companyId } = await access(googleAuthId, tx);
|
|
|
|
const existing = await runner.query(getSql, { id, companyId });
|
|
if (!existing.rows[0]) {
|
|
throw new Error('Attribute name not found');
|
|
}
|
|
|
|
const name = input.name !== undefined ? input.name?.trim() : existing.rows[0].name;
|
|
if (!name) {
|
|
throw new Error('Name required');
|
|
}
|
|
const sort = input.sort !== undefined && Number.isInteger(input.sort) ? input.sort : existing.rows[0].sort;
|
|
const exclusive = input.exclusive !== undefined ? (Boolean(input.exclusive) ? 1 : 0) : existing.rows[0].exclusive;
|
|
|
|
await runner.query(updateSql, {
|
|
id,
|
|
companyId,
|
|
name,
|
|
sort,
|
|
exclusive,
|
|
});
|
|
|
|
return {
|
|
id,
|
|
name,
|
|
sort,
|
|
exclusive: Boolean(exclusive),
|
|
values: parseValues(existing.rows[0].valuesJson),
|
|
};
|
|
};
|
|
}
|