46 lines
1.0 KiB
TypeScript
46 lines
1.0 KiB
TypeScript
import { v4 } from 'uuid';
|
|
|
|
interface SlugOptions {
|
|
year: boolean;
|
|
month: boolean;
|
|
day: boolean;
|
|
hour: boolean;
|
|
minute: boolean;
|
|
second: boolean;
|
|
random: boolean;
|
|
separator: string;
|
|
}
|
|
|
|
const defaultSlugOptions: SlugOptions = {
|
|
year: true,
|
|
month: true,
|
|
day: true,
|
|
hour: true,
|
|
minute: true,
|
|
second: false,
|
|
random: false,
|
|
separator: '',
|
|
};
|
|
|
|
export const generateUniqueSlug = (
|
|
options: Partial<SlugOptions> = {},
|
|
): string => {
|
|
const { year, month, day, hour, minute, second, random, separator } = {
|
|
...defaultSlugOptions,
|
|
...options,
|
|
};
|
|
|
|
const date = new Date();
|
|
const parts = [
|
|
year ? date.getFullYear() : '',
|
|
month ? String(date.getMonth() + 1).padStart(2, '0') : '',
|
|
day ? String(date.getDate()).padStart(2, '0') : '',
|
|
hour ? String(date.getHours()).padStart(2, '0') : '',
|
|
minute ? String(date.getMinutes()).padStart(2, '0') : '',
|
|
second ? String(date.getSeconds()).padStart(2, '0') : '',
|
|
random ? '-' + v4() : '',
|
|
].filter(Boolean);
|
|
|
|
return parts.join(separator);
|
|
};
|