17 lines
706 B
TypeScript
17 lines
706 B
TypeScript
|
import {cryptoRandomDictionary} from "wms-core/Utils";
|
||
|
import config from "config";
|
||
|
import FileModel from "./models/FileModel";
|
||
|
import {ServerError} from "wms-core/HttpError";
|
||
|
|
||
|
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.');
|
||
|
};
|