UNPKG

@adonisjs/lucid-slugify

Version:

Generate and persist unique slugs in your database via Lucid models

87 lines (86 loc) 2.78 kB
import type { LucidModel } from '@adonisjs/lucid/types/model'; import type { SlugifierConfig, SlugifyStrategyContract } from './types.js'; /** * Slugifier expsoes the API to create unique slugs using a slugify strategy. * You can specify the model for which the slugs should be generated and * an array of fields to use for computing the slug raw value. * * @example * ```ts * const slugifier = new Slugifier(Post, 'slug', new ShortId(), { * fields: ['title'] * }) * * const post = new Post() * post.title = 'Hello world' * * const slug = await slugifier.makeSlug(post) * * // Set the post.slug property * await slugifier.createSlug(post) * * // Set the post.slug property when its source fields has been modified * await slugifier.updateSlug(post) * ``` */ export declare class Slugifier<Model extends LucidModel, SlugField extends keyof InstanceType<Model>> { #private; /** * Convert a value to a URL-safe slug. Feel free to replace this * method with a custom implementation. */ static slugify(value: string, options: { separator: string; lower: boolean; }): string; constructor(model: Model, slugField: SlugField, strategy: SlugifyStrategyContract, config: SlugifierConfig<InstanceType<Model>, SlugField>); /** * Create a new unique slug using the provided strategy and sets * the value for the "forField" property on the model instance. * * @note * This method does not issue a database query, instead it is meant * to be used within a `beforeCreate` hook * * @example * ```ts * * const post = new Post() * post.title = 'Hello world' * * await slugifier.createSlug(post) * post.slug // hello-world * ``` */ createSlug(row: InstanceType<Model>): Promise<void>; /** * Updates the value for the existing slug property when its source * fields have been mutated. * * You can disable slug updates using the {@link SlugifierConfig.allowUpdates} * config option. * * @note * This method does not issue a database query, instead it is meant * to be used within a `beforeUpdate` hook. * * @example * ```ts * * const post = Post.findOrFail(1) * post.title = 'Updated title' * * await slugifier.updateSlug(post) * post.slug // updated-title * ``` */ updateSlug(row: InstanceType<Model>): Promise<void>; /** * Creates a slug for a given model instance using the values from * the source fields. * * A `null` value will be returned when one of the source fields * have `undefined` or `null` values. */ makeSlug(modelInstance: InstanceType<Model>): Promise<string | null>; }