86 lines
2.8 KiB
JavaScript
86 lines
2.8 KiB
JavaScript
import {
|
|
CREATE as MSSQL_CREATE,
|
|
GET_NEXT_SORT as MSSQL_GET_NEXT_SORT,
|
|
} from '../../providers/mssql/queries/attributevalue.js';
|
|
import {
|
|
CREATE as SQLITE_CREATE,
|
|
GET_NEXT_SORT as SQLITE_GET_NEXT_SORT,
|
|
} from '../../providers/sqlite3/queries/attributevalue.js';
|
|
import {
|
|
GET_BY_COMPANY_AND_ID as MSSQL_GET_ATTR,
|
|
} from '../../providers/mssql/queries/attributename.js';
|
|
import {
|
|
GET_BY_COMPANY_AND_ID as SQLITE_GET_ATTR,
|
|
} from '../../providers/sqlite3/queries/attributename.js';
|
|
import { isUniqueConstraintError } from '../../providers/provider.js';
|
|
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
|
|
import makeRunner from '../runner.js';
|
|
|
|
export default function create(provider) {
|
|
const access = resolveSelectedCompanyAccess(provider);
|
|
const isSqlite = provider?.dialect === 'sqlite3';
|
|
const getAttrSql = isSqlite ? SQLITE_GET_ATTR : MSSQL_GET_ATTR;
|
|
const getSortSql = isSqlite ? SQLITE_GET_NEXT_SORT : MSSQL_GET_NEXT_SORT;
|
|
const createSql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
|
|
|
|
/**
|
|
* Creates an attribute value under a given attribute.
|
|
*
|
|
* @param {number} googleAuthId - The id of the Google auth user.
|
|
* @param {number} attributeId - The attribute id.
|
|
* @param {object} input - Input value data.
|
|
* @param {string} input.value - The value text.
|
|
* @param {number} [input.sort] - Optional sort order.
|
|
* @param {object} [tx] - Optional transaction.
|
|
* @returns {Promise<{id: number, attributeId: number, value: string, sort: number}>}
|
|
*
|
|
* @throws {Error} If the value is missing, the attribute is unknown, or the value already exists for the attribute.
|
|
*/
|
|
return async (googleAuthId, attributeId, input = {}, tx) => {
|
|
const attrId = Number(attributeId);
|
|
if (!Number.isInteger(attrId) || attrId <= 0) {
|
|
throw new Error('Invalid attributeId');
|
|
}
|
|
const value = input.value?.trim();
|
|
if (!value) {
|
|
throw new Error('Value required');
|
|
}
|
|
|
|
const runner = makeRunner(provider, tx);
|
|
const { companyId } = await access(googleAuthId, tx);
|
|
|
|
const attrRes = await runner.query(getAttrSql, { id: attrId, companyId });
|
|
if (!attrRes.rows[0]) {
|
|
throw new Error('Attribute name not found');
|
|
}
|
|
|
|
let sort = input.sort;
|
|
if (sort == null || !Number.isInteger(sort)) {
|
|
const next = await runner.query(getSortSql, { attributeId: attrId });
|
|
sort = next.rows[0].sort;
|
|
}
|
|
|
|
let result;
|
|
try {
|
|
result = await runner.query(createSql, {
|
|
attributeId: attrId,
|
|
value,
|
|
sort,
|
|
});
|
|
} catch (err) {
|
|
if (isUniqueConstraintError(err)) {
|
|
throw new Error('Attribute value already exists');
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
const id = result.rows[0]?.id ?? result.insertId;
|
|
return {
|
|
id,
|
|
attributeId: attrId,
|
|
value,
|
|
sort,
|
|
};
|
|
};
|
|
}
|