import type { RouteParamsGeneric } from '#vue-router'; export type Slug = { name: string; id: number }; export type SlugRecord = Record; export function parseSlug(slug: string): null | Slug { const result = /^(?(?:\w+-)*)(?\d*)$/.exec(slug); if ( result === null || result.groups === undefined || result.groups.id === undefined || result.groups.id.length <= 0 ) { return null; } const { name, id } = result.groups!; return { name: name .substring(0, name.length - 1) .split('-') .map((w) => `${w.substring(0, 1).toUpperCase()}${w.substring(1)}`) .join(' '), id: parseInt(id) }; } export function checkSlug(routeParams: RouteParamsGeneric): null | SlugRecord { const slugs = Object.keys(routeParams).filter( (k) => k.endsWith('Slug') && typeof routeParams[k] === 'string' ); const parsed = slugs.map((s) => parseSlug(routeParams[s] as string)); if (parsed.some((s) => s === null)) { return null; } return Object.fromEntries(slugs.map((slugKey, i) => [slugKey, parsed[i]!])); }