Created
June 5, 2024 18:24
-
-
Save vinicioslc/3b9fa1745e4e5a4f89517ddbe5e1eb24 to your computer and use it in GitHub Desktop.
Add random value to unique columns in adonisjs v4.1 to allow add again random columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nanoid = require('nanoid') // npm i nanoid@3 | |
/** @type {import('@adonisjs/lucid/src/Database')} */ | |
const Database = use('Database') | |
module.exports = { | |
removeUniqueWithData, | |
} | |
async function removeUniqueWithData( | |
tableName, | |
column, | |
charCountToAdd = 5, | |
alphabet = undefined, | |
randomCharSpace = '', | |
allowEmpty = false, | |
) { | |
console.error('👀 Searching Duplicates For Table: [', tableName, '] Column: [', column, ']') | |
const rowsFound = await Database.table(tableName) | |
.whereNotNull(column) | |
.orderBy('id', 'desc') | |
const duplicates = {} | |
for (const cRow of rowsFound) { | |
const isNotEmpty = cRow[column] !== '' | |
const canScanDuplicated = !allowEmpty && isNotEmpty | |
if (canScanDuplicated) { | |
if (duplicates[column]?.first[column] === cRow[column]) { | |
duplicates[column].duplicates = [...duplicates[column].duplicates, cRow] | |
} else { | |
duplicates[column] = { first: cRow, duplicates: [] } | |
continue | |
} | |
} | |
} | |
for (const dupKey in duplicates) { | |
if (Object.hasOwnProperty.call(duplicates, dupKey)) { | |
const element = duplicates[dupKey] | |
if (element.duplicates.length) { | |
console.error('🧬 Has Duplicates', element) | |
for (let dup of element.duplicates) { | |
const randomStr = alphabet | |
? nanoid.customAlphabet(alphabet, charCountToAdd - 1) | |
: nanoid.nanoid(charCountToAdd - 1) | |
const newValue = dup[column] + randomCharSpace + randomStr | |
await Database.table(tableName) | |
.where('id', dup.id) | |
.update({ [column]: newValue }) | |
console.error('🧬 Duplicated Entry Replaced', dup[column], '->', newValue) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment