| 3 | import { slug } from './slug'; |
| 4 | |
| 5 | export async function getId(tableName: 'project' | 'dashboard', name: string) { |
| 6 | const newId = slug(name); |
| 7 | if (!db[tableName]) { |
| 8 | throw new Error('Table does not exists'); |
| 9 | } |
| 10 | |
| 11 | if (!('findUnique' in db[tableName])) { |
| 12 | throw new Error('findUnique does not exists'); |
| 13 | } |
| 14 | |
| 15 | // @ts-expect-error |
| 16 | const existingProject = await db[tableName].findUnique({ |
| 17 | where: { |
| 18 | id: newId, |
| 19 | }, |
| 20 | }); |
| 21 | |
| 22 | function random(str: string) { |
| 23 | const numbers = Math.floor(1000 + Math.random() * 9000); |
| 24 | if (str.match(/-\d{4}$/g)) { |
| 25 | return str.replace(/-\d{4}$/g, `-${numbers}`); |
| 26 | } |
| 27 | return `${str}-${numbers}`; |
| 28 | } |
| 29 | |
| 30 | if (existingProject) { |
| 31 | return getId(tableName, random(name)); |
| 32 | } |
| 33 | |
| 34 | return newId; |
| 35 | } |