Files
modstagram-back/utils/usernameSuggestions.js
root c62e4c0577 fix: resolve MongoDB connection and port configuration issues
- Added dotenv configuration for environment variables
- Fixed MongoDB connection string loading
- Configured server port to 3005
- Updated cron jobs for expired messages
2026-07-11 14:06:46 +03:30

57 lines
1.8 KiB
JavaScript

const { validateUsername, USERNAME_MAX_LENGTH } = require('./usernameValidation')
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const isUsernameTaken = async (UserModel, userName, excludeUserId) => {
const existing = await UserModel.findOne({
user_name: { $regex: new RegExp(`^${escapeRegex(userName)}$`, 'i') }
})
if (!existing) return false
if (excludeUserId && existing._id.toString() === excludeUserId) return false
return true
}
const buildCandidates = (base, attempt) => {
const random2 = () => String(Math.floor(Math.random() * 90 + 10))
const random3 = () => String(Math.floor(Math.random() * 900 + 100))
const random4 = () => String(Math.floor(Math.random() * 9000 + 1000))
const builders = [
() => `${base}_${random2()}`,
() => `${base}.${random2()}`,
() => `${base}${random3()}`,
() => `${base}-${random2()}`,
() => `${base}_${random3()}`,
() => `${base}${random4()}`,
]
return builders[attempt % builders.length]()
}
const trimToMax = (value) =>
value.length > USERNAME_MAX_LENGTH ? value.slice(0, USERNAME_MAX_LENGTH) : value
const generateUsernameSuggestions = async (UserModel, baseUserName, excludeUserId) => {
const base = trimToMax(baseUserName.trim().toLowerCase())
const suggestions = []
let attempt = 0
while (suggestions.length < 3 && attempt < 30) {
const candidate = trimToMax(buildCandidates(base, attempt))
attempt += 1
if (validateUsername(candidate)) continue
if (suggestions.includes(candidate)) continue
if (await isUsernameTaken(UserModel, candidate, excludeUserId)) continue
suggestions.push(candidate)
}
return suggestions
}
module.exports = {
generateUsernameSuggestions,
}