ily.li/src/SlugGenerator.ts

18 lines
699 B
TypeScript
Raw Normal View History

2020-11-22 13:49:08 +01:00
import {cryptoRandomDictionary} from "swaf/Utils";
2020-07-06 10:49:18 +02:00
import config from "config";
import FileModel from "./models/FileModel";
2020-11-22 13:49:08 +01:00
import {ServerError} from "swaf/HttpError";
2020-07-06 10:49:18 +02:00
const SLUG_DICTIONARY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
export default async function generateSlug(tries: number): Promise<string> {
let i = 0;
do {
const slug = cryptoRandomDictionary(config.get<number>('newlyGeneratedSlugSize'), SLUG_DICTIONARY);
if (!await FileModel.getBySlug(slug)) {
return slug;
}
i++;
} while (i < tries);
throw new ServerError('Failed to generate slug; newly generated slug size should be increased by 1.');
2020-11-22 13:49:08 +01:00
};