-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathutils.ts
35 lines (28 loc) · 924 Bytes
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* SPDX-FileCopyrightText: 2016-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */
import { Knex } from "knex";
import { customAlphabet } from "nanoid/async";
// An alphabet for generating short IDs.
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
// Creates a function that generates a short ID of specified length.
export function createNewId(
db: Knex,
table: string,
size: number
): (unique: boolean) => Promise<string> {
const generateId = customAlphabet(alphabet, size);
return async function newId(unique = true) {
let id = await generateId();
// Ensures that the generated ID is unique
while (unique) {
const record = await db.table(table).where({ id }).first(db.raw(1));
if (record) {
console.warn(`Re-generating new ${table} ID.`);
id = await generateId();
} else {
break;
}
}
return id;
};
}