FixerUG
DTDrizzle Team
•Created by alka_99 on 3/18/2024 in #help
Auto Increment custom id with prefix GRO
This myt be hacky but has proved to be very finctional for us. We use a function like this for every table that needs those incremental references:
export async function genAccountCode() {
const suffix = 'GRO';
const result = await db.query.accountsTable.findMany({
where: (x, { like }) => like(x.actCode,
${suffix}%
),
columns: {
actCode: true,
},
orderBy: [desc(accountsTable.actCode)],
limit: 1,
});
//checking that we have a valid result
const lastRefNo = result && result.length > 0 ? result[0]?.actCode : null;
try {
//checking that lastRefNo is not null
if (lastRefNo != null) {
// here you remove(trim) the suffix to be able to increment it.
const trimmed = lastRefNo.substring(3);
// here u increment the number part by 1
const incremented = (parseInt(trimmed) + 1).toString();
// put the number of zeros needed, e.g pad 3, on the incremented value, the put the suffix to get new code to use.
const newActCode = ${suffix}${incremented.padStart(3, '0')}
;
return newActCode;
} else {
return ${suffix}001
;
}
} catch (error) {
throw new Error('Error generating Account Code');
}
}11 replies