u
This commit is contained in:
74
src/store/attributevalue/create.js
Normal file
74
src/store/attributevalue/create.js
Normal file
@@ -0,0 +1,74 @@
|
||||
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 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}>}
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
const result = await runner.query(createSql, {
|
||||
attributeId: attrId,
|
||||
value,
|
||||
sort,
|
||||
});
|
||||
|
||||
const id = result.rows[0]?.id ?? result.insertId;
|
||||
return {
|
||||
id,
|
||||
attributeId: attrId,
|
||||
value,
|
||||
sort,
|
||||
};
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user