| 9 | }); |
| 10 | |
| 11 | async function main() { |
| 12 | |
| 13 | try { |
| 14 | await prisma.user.findFirstOrThrow({ where: { email: 'alice@prisma.io' } }) |
| 15 | } catch { |
| 16 | const consoleMessage = ` |
| 17 | User alice@prisma.io not found. Please run the seed script before running this script. |
| 18 | You can run the seed script via the following command: |
| 19 | |
| 20 | npx prisma db seed |
| 21 | `; |
| 22 | console.error(consoleMessage); |
| 23 | return |
| 24 | } |
| 25 | |
| 26 | // Retrieve all published posts |
| 27 | const allPosts = await prisma.post.findMany({ |
| 28 | where: { published: true }, |
| 29 | }) |
| 30 | console.log('Retrieved all published posts: ', allPosts) |
| 31 | |
| 32 | // Create a new post (written by an already existing user with email alice@prisma.io) |
| 33 | const newPost = await prisma.post.create({ |
| 34 | data: { |
| 35 | title: "Join us for another episode of What's new in Prisma", |
| 36 | content: 'https://youtube.com/playlist?list=PLn2e1F9Rfr6l1B9RP0A9NdX7i7QIWfBa7', |
| 37 | published: false, |
| 38 | author: { |
| 39 | connect: { |
| 40 | email: 'alice@prisma.io', |
| 41 | }, |
| 42 | }, |
| 43 | }, |
| 44 | }) |
| 45 | console.log('Created a new post:', newPost) |
| 46 | |
| 47 | // Publish the new post |
| 48 | const updatedPost = await prisma.post.update({ |
| 49 | where: { |
| 50 | id: newPost.id, |
| 51 | }, |
| 52 | data: { |
| 53 | published: true, |
| 54 | }, |
| 55 | }) |
| 56 | console.log(`Published the newly created post: `, updatedPost) |
| 57 | |
| 58 | // Retrieve all posts by user with email alice@prisma.io |
| 59 | const postsByUser = await prisma.user |
| 60 | .findUnique({ |
| 61 | where: { |
| 62 | email: 'alice@prisma.io', |
| 63 | }, |
| 64 | }) |
| 65 | .posts() |
| 66 | console.log(`Retrieved all posts from a specific user: `, postsByUser) |
| 67 | } |
| 68 | |