Created
November 16, 2022 18:06
-
-
Save ChristopherLMiller/ff0814c750b2abbaa21e42ae22358445 to your computer and use it in GitHub Desktop.
How to make slug unique while inserting... not generic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// we use this variable to keep track of the db insertion being successful or not | |
let result = null; | |
let counter = 0; | |
do { | |
try { | |
// Handle singular item | |
const title = newItems.title; | |
const slug = slugify(`${title}${counter ? '-' + counter : ''}`, { | |
lower: true, | |
strict: true, | |
}); | |
result = await this.prisma.postCategory.create({ | |
data: { title, slug }, | |
}); | |
} catch (error) { | |
if (error instanceof Prisma.PrismaClientKnownRequestError) { | |
if (error.code === 'P2002') { | |
// Error code is from prisma docs https://www.prisma.io/docs/reference/api-reference/error-reference | |
// Unique constraint fail, increment the counter | |
counter++; | |
} | |
} else { | |
// Idk what else could fail it, just throw the error | |
throw e; | |
} | |
} | |
} while (!result && counter < 10); // loop while result is null and counter is less than 10 | |
return result; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment