31 lines
868 B
JavaScript
31 lines
868 B
JavaScript
'use strict';
|
||
|
||
const crypto = require('crypto');
|
||
|
||
const MIN_CODE = 10000000;
|
||
const MAX_CODE = 100000000;
|
||
|
||
/** Generate a random 8-digit numeric string (10000000–99999999). */
|
||
const generateCode = () => String(crypto.randomInt(MIN_CODE, MAX_CODE));
|
||
|
||
/**
|
||
* Allocate a unique code for a Mongoose model field.
|
||
* Retries on collision up to maxAttempts times.
|
||
*/
|
||
const generateUniqueCode = async (Model, field = 'uniqueCode', maxAttempts = 24) => {
|
||
if (!Model) throw new Error('Model is required to generate a unique code');
|
||
|
||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||
const code = generateCode();
|
||
const exists = await Model.exists({ [field]: code });
|
||
if (!exists) return code;
|
||
}
|
||
|
||
throw new Error(`Could not generate a unique ${field} after ${maxAttempts} attempts`);
|
||
};
|
||
|
||
module.exports = {
|
||
generateCode,
|
||
generateUniqueCode
|
||
};
|