Hi @fierce wind 👋
One way to go about this is to:
- Perform the S3 upload operation before any database transaction. This ensures that the network request is completed successfully before proceeding with database operations.
- Use a Transaction to Create the Playlist Entry: Once the image is successfully uploaded, start a transaction to create the playlist entry and update it with the thumbnail URL.
for example:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
async function uploadThumbnailToS3(file, playlistId) {
const params = {
Bucket: 'your-bucket-name',
Key: `thumbnails/${playlistId}.jpg`,
Body: file,
ContentType: 'image/jpeg'
};
return s3.upload(params).promise();
}
async function createPlaylistWithThumbnail(prisma, file) {
try {
const newPlaylist = await prisma.playlist.create({
data: {
}
});
const playlistId = newPlaylist.id;
await uploadThumbnailToS3(file, playlistId);
await prisma.$transaction(async (tx) => {
await tx.playlist.update({
where: { id: playlistId },
data: {
thumbnailUrl: `https://your-bucket-name.s3.amazonaws.com/thumbnails/${playlistId}.jpg`
}
});
});
} catch (error) {
console.error('Failed to upload thumbnail or update playlist:', error);
throw error;
}
}