63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
import {
|
|
CREATE as MSSQL_CREATE,
|
|
GET_NEXT_SORT as MSSQL_GET_NEXT_SORT,
|
|
} from '../../providers/mssql/queries/attributename.js';
|
|
import {
|
|
CREATE as SQLITE_CREATE,
|
|
GET_NEXT_SORT as SQLITE_GET_NEXT_SORT,
|
|
} from '../../providers/sqlite3/queries/attributename.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 getSortSql = isSqlite ? SQLITE_GET_NEXT_SORT : MSSQL_GET_NEXT_SORT;
|
|
const createSql = isSqlite ? SQLITE_CREATE : MSSQL_CREATE;
|
|
|
|
/**
|
|
* Creates an attribute name for the user's selected company.
|
|
*
|
|
* @param {number} googleAuthId - The id of the Google auth user.
|
|
* @param {object} input - The attribute name input.
|
|
* @param {string} input.name - The attribute name.
|
|
* @param {number} [input.sort] - Optional sort order.
|
|
* @param {boolean} [input.exclusive=false] - Whether values are mutually exclusive on an article.
|
|
* @param {object} [tx] - Optional transaction.
|
|
* @returns {Promise<{id: number, name: string, sort: number, exclusive: boolean, values: Array}>}
|
|
*/
|
|
return async (googleAuthId, input = {}, tx) => {
|
|
const name = input.name?.trim();
|
|
if (!name) {
|
|
throw new Error('Name required');
|
|
}
|
|
|
|
const runner = makeRunner(provider, tx);
|
|
const { companyId } = await access(googleAuthId, tx);
|
|
|
|
let sort = input.sort;
|
|
if (sort == null || !Number.isInteger(sort)) {
|
|
const next = await runner.query(getSortSql, { companyId });
|
|
sort = next.rows[0].sort;
|
|
}
|
|
|
|
const exclusive = Boolean(input.exclusive) ? 1 : 0;
|
|
|
|
const result = await runner.query(createSql, {
|
|
companyId,
|
|
name,
|
|
sort,
|
|
exclusive,
|
|
});
|
|
|
|
const id = result.rows[0]?.id ?? result.insertId;
|
|
return {
|
|
id,
|
|
name,
|
|
sort,
|
|
exclusive: Boolean(exclusive),
|
|
values: [],
|
|
};
|
|
};
|
|
}
|