Skip to content

Instantly share code, notes, and snippets.

@acidiney
Created February 4, 2024 09:08
Show Gist options
  • Save acidiney/621e19d9e11a48c194a9809f318ba757 to your computer and use it in GitHub Desktop.
Save acidiney/621e19d9e11a48c194a9809f318ba757 to your computer and use it in GitHub Desktop.
// utils/slugify-adapter-impl.ts
import db from '@adonisjs/lucid/services/db'
import slugify from 'slugify'
export const slugifyAdapter = async (
data: string,
options: {
tableName: string
fieldName: string
}
) => {
const separator = '-'
let slug = slugify.default(data, {
replacement: separator,
lower: true,
strict: true,
trim: true,
})
const checkSlugOnDatabase = await db
.from(options.tableName)
.select({ slugDb: options.fieldName })
.where(options.fieldName, 'like', `${slug}%`)
if (!checkSlugOnDatabase.length) {
return slug
}
let maximumSlugNumber = 0
for (const { slugDb } of checkSlugOnDatabase) {
const slugParts = slugDb.split(separator)
const lastPart = slugParts[slugParts.length - 1]
if (Number.isNaN(lastPart)) {
continue
}
if (Number(lastPart) > maximumSlugNumber) {
maximumSlugNumber = Number(lastPart)
}
}
return `${slug}${separator}${maximumSlugNumber + 1}`
}
// models/user-model.ts
@beforeSave()
static async setSlug(user: UserModel) {
if (!user.slug) {
user.slug = await slugifyAdapter(user.fullName, {
fieldName: 'slug',
tableName: 'users',
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment