I'm trying to create a model where there's a many-to-many relation between 2 types, Movie and Genre.
I retrieve a list of movies from an external data source asynchronously, create each in my own database if it's not already created, and return the movie.
const retrieveList = async () => {
const results = await API.getMovies();
return results.map((item) => getMovieItem(item.id));
}
const getMovieItem = async (movieId) => {
// see if is already in database
const movie = await prisma.movie.findUnique({
where: { tmdbId: movieId },
});
if (movie) {
return movie;
} else {
// create and return if doesn't exist
const details = await API.getDetails(movieId);
const genresData = details.genres.map((genre) => ({
create: {
name: genre.name,
},
where: {
name: genre.name
},
}));
return prisma.movie.create({
data: {
title: details.title,
description: details.overview,
genres: {
connectOrCreate: genresData,
},
},
select: {
tmdbId: true,
id: true,
title: true,
description: true,
//...
},
});
}
};
the problem is that there seems to be some sort of inconsistency where if the connection to the external API is slow enough in some runs, everything seems to be working fine; but also if it's fast enough, it throws the error:
Invalid `prisma.movie.create()` invocation:
Unique constraint failed on the fields: (`name`)"
likely because it is trying to create a genre that's already created instead of connecting it.