Skip to content

Instantly share code, notes, and snippets.

@ChristopherLMiller
Created November 16, 2022 18:06
Show Gist options
  • Save ChristopherLMiller/ff0814c750b2abbaa21e42ae22358445 to your computer and use it in GitHub Desktop.
Save ChristopherLMiller/ff0814c750b2abbaa21e42ae22358445 to your computer and use it in GitHub Desktop.
How to make slug unique while inserting... not generic
// 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