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