Files

31 lines
868 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const crypto = require('crypto');
const MIN_CODE = 10000000;
const MAX_CODE = 100000000;
/** Generate a random 8-digit numeric string (1000000099999999). */
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
};