Files
dashlibstorage/src/store/numbers/peekNumber.js
2026-10-12 22:32:21 +02:00

56 lines
1.8 KiB
JavaScript

import {
ENSURE_TYPE as MSSQL_ENSURE_TYPE,
GET_FOR_UPDATE as MSSQL_GET_FOR_UPDATE,
} from '../../providers/mssql/queries/numbers.js';
import {
ENSURE_TYPE as SQLITE_ENSURE_TYPE,
GET_FOR_UPDATE as SQLITE_GET_FOR_UPDATE,
} from '../../providers/sqlite3/queries/numbers.js';
import makeRunner from '../runner.js';
function formatNumber(prefix, padding, num) {
const p = prefix ?? '';
const nStr = String(num);
const padded = padding > 0 ? nStr.padStart(padding, '0') : nStr;
return `${p}${padded}`;
}
export default function peekNumber(provider) {
const isSqlite = provider?.dialect === 'sqlite3';
const ensureSql = isSqlite ? SQLITE_ENSURE_TYPE : MSSQL_ENSURE_TYPE;
const getSql = isSqlite ? SQLITE_GET_FOR_UPDATE : MSSQL_GET_FOR_UPDATE;
/**
* Returns the next number for a company and type without consuming it.
*
* @param {number} companyId - The id of the company.
* @param {string} type - The number type (e.g. `'entity'`, `'sku'`).
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<string>} The next number.
*
* @example
* const number = await store.numbers.peek(1, 'entity');
* // => '1'
*/
return async (companyId, type, tx) => {
const doPeek = async (runner) => {
const prefix = type === 'shipment' ? '-L-' : '';
await runner.query(ensureSql, { companyId, type, prefix });
const res = await runner.query(getSql, { companyId, type });
const row = res.rows[0];
if (!row) {
throw new Error('Number type not found for company');
}
return formatNumber(row.prefix, row.padding, row.next);
};
if (tx) {
return doPeek(makeRunner(provider, tx));
}
if (typeof provider?.transaction === 'function') {
return provider.transaction(doPeek);
}
return doPeek(makeRunner(provider));
};
}