From e85117b2c7e7125aa61b891fdb37ca438ddf1179 Mon Sep 17 00:00:00 2001 From: Eric Date: Sat, 12 Nov 2022 20:23:15 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20add=20-=20api=20generation?= =?UTF-8?q?Gain=20,=20api=20superadmin=20,=20readme=20,=20fichier=20de=20s?= =?UTF-8?q?eed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env | 4 + README.md | 22 ++- components/Layout.tsx | 2 +- docker-compose.yaml | 41 +++++ enum/cadeaux.enum.ts | 7 + enum/role.enum.ts | 5 + package-lock.json | 84 ++++++---- package.json | 9 +- pages/api/gain/index.ts | 107 +++++++++++++ pages/api/profile/index.ts | 1 + pages/api/superadmin/index.ts | 36 +++++ pages/index.tsx | 109 ++++++++----- pages/profile.tsx | 139 ++++++++++------- prisma/dev.db | Bin 65536 -> 0 bytes .../20221109202932_init/migration.sql | 70 --------- .../migrations/20221110093840_/migration.sql | 10 -- .../migrations/20221110112827_/migration.sql | 21 --- .../migrations/20221110113201_/migration.sql | 21 --- .../migrations/20221112185745_/migration.sql | 144 ++++++++++++++++++ prisma/migrations/migration_lock.toml | 2 +- prisma/schema.prisma | 35 ++++- prisma/seed.ts | 90 +++++------ prisma/seed/gains.ts | 48 ++++++ prisma/seed/produits.ts | 24 +++ prisma/seed/user.ts | 47 ++++++ 25 files changed, 768 insertions(+), 310 deletions(-) create mode 100644 docker-compose.yaml create mode 100644 enum/cadeaux.enum.ts create mode 100644 enum/role.enum.ts create mode 100644 pages/api/gain/index.ts create mode 100644 pages/api/superadmin/index.ts delete mode 100644 prisma/dev.db delete mode 100644 prisma/migrations/20221109202932_init/migration.sql delete mode 100644 prisma/migrations/20221110093840_/migration.sql delete mode 100644 prisma/migrations/20221110112827_/migration.sql delete mode 100644 prisma/migrations/20221110113201_/migration.sql create mode 100644 prisma/migrations/20221112185745_/migration.sql create mode 100644 prisma/seed/gains.ts create mode 100644 prisma/seed/produits.ts create mode 100644 prisma/seed/user.ts diff --git a/.env b/.env index 1757eb4..d60be06 100644 --- a/.env +++ b/.env @@ -12,3 +12,7 @@ GOOGLE_CLIENT_SECRET=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 # Email (magic link) EMAIL_SERVER=smtp://2bfdbee5372880:af828174d7f2ad@smtp.mailtrap.io:2525 EMAIL_FROM=thetiptop@test.com + +DATABASE_URL="postgres://postgres:postgrespwd@localhost:5432/thetiptop" + + diff --git a/README.md b/README.md index 8365658..ee9838c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,24 @@ -# Fullstack Authentication Example with Next.js and NextAuth.js +# Fullstack App with Next.js and NextAuth.js + +docker compose up +pour créer les containers avec la base de donnée PosgreSQL et PGAdmin + +npm install + +npx prisma migrate dev +va hydrater la db et jouer le fichier de seed + +npx prisma db +va reset la db et re-executer le fichier de seed + +npm run dev +va lancer l'application sur le localhost:3000 + +npx prisma studio +pour naviguer dans la db via le localhost:5555 + +*********************************** + This example shows how to implement a **fullstack app in TypeScript with [Next.js](https://nextjs.org/)** using [React](https://reactjs.org/) (frontend), [Next.js API routes](https://nextjs.org/docs/api-routes/introduction) and [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client) (backend). It also demonstrates how to implement authentication using [NextAuth.js](https://next-auth.js.org/). The example uses an SQLite database file with some initial dummy data which you can find at [`./prisma/dev.db`](./prisma/dev.db). diff --git a/components/Layout.tsx b/components/Layout.tsx index 2d1bbdc..6194bbe 100644 --- a/components/Layout.tsx +++ b/components/Layout.tsx @@ -5,7 +5,7 @@ type Props = { children?: React.ReactNode; }; -const Layout = ({children} : Props) => ( +const Layout = ({ children }: Props) => (
{children}
diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..afabab8 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,41 @@ +version: '3.5' + +services: + postgres: + container_name: postgres_container + image: postgres + environment: + POSTGRES_USER: ${POSTGRES_USER:-postgres} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgrespwd} + PGDATA: /data/postgres + volumes: + - postgres:/data/postgres + ports: + - "5432:5432" + networks: + - postgres + restart: unless-stopped + + pgadmin: + container_name: pgadmin_container + image: dpage/pgadmin4 + environment: + PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org} + PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin} + PGADMIN_CONFIG_SERVER_MODE: 'False' + volumes: + - pgadmin:/var/lib/pgadmin + + ports: + - "${PGADMIN_PORT:-5050}:80" + networks: + - postgres + restart: unless-stopped + +networks: + postgres: + driver: bridge + +volumes: + postgres: + pgadmin: diff --git a/enum/cadeaux.enum.ts b/enum/cadeaux.enum.ts new file mode 100644 index 0000000..28e0155 --- /dev/null +++ b/enum/cadeaux.enum.ts @@ -0,0 +1,7 @@ +export enum Cadeaux { + CoffretDecouvert69 = 1, + CoffretDecouvert39 = 2, + TheSignature = 3, + TheDetox = 4, + Infuseur = 5, +} \ No newline at end of file diff --git a/enum/role.enum.ts b/enum/role.enum.ts new file mode 100644 index 0000000..210d216 --- /dev/null +++ b/enum/role.enum.ts @@ -0,0 +1,5 @@ +export enum Role { + USER = 'USER', + ADMIN = 'ADMIN', + SUPERADMIN = 'SUPERADMIN' +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 3f3befa..ddd9f6d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,8 +11,9 @@ "dependencies": { "@hookform/resolvers": "^2.9.10", "@next-auth/prisma-adapter": "1.0.5", - "@prisma/client": "4.6.0", + "@prisma/client": "^4.6.1", "bootstrap": "^5.2.2", + "chance": "^1.1.9", "next": "13.0.2", "next-auth": "4.16.4", "react": "18.2.0", @@ -22,10 +23,11 @@ "yup": "^0.32.11" }, "devDependencies": { + "@types/chance": "^1.1.3", "@types/next-auth": "3.13.0", "@types/node": "18.11.9", "@types/react": "18.0.25", - "prisma": "4.6.0", + "prisma": "^4.6.1", "ts-node": "10.9.1", "typescript": "4.8.4" } @@ -323,12 +325,12 @@ } }, "node_modules/@prisma/client": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.0.tgz", - "integrity": "sha512-D9LaQinDxOHinRpcJTw2tjMtjhc9HTP+aF1IRd2oLldp/8TiwIfxK8x17OhBBiX4y1PzbJXXET7kS+5wB3es/w==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.1.tgz", + "integrity": "sha512-M1+NNrMzqaOIxT7PBGcTs3IZo7d1EW/+gVQd4C4gUgWBDGgD9AcIeZnUSidgWClmpMSgVUdnVORjsWWGUameYA==", "hasInstallScript": true, "dependencies": { - "@prisma/engines-version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3" + "@prisma/engines-version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32" }, "engines": { "node": ">=14.17" @@ -343,16 +345,16 @@ } }, "node_modules/@prisma/engines": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.0.tgz", - "integrity": "sha512-S+72PAl0zTCbIGou1uXD/McvzdtP+bjOs0LRmGZfcOQcVqR9x/0f6Z+dqpUU0zIcqHEl+0DOB8UXaTwRvssFsQ==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.1.tgz", + "integrity": "sha512-3u2/XxvxB+Q7cMXHnKU0CpBiUK1QWqpgiBv28YDo1zOIJE3FCF8DI2vrp6vuwjGt5h0JGXDSvmSf4D4maVjJdw==", "devOptional": true, "hasInstallScript": true }, "node_modules/@prisma/engines-version": { - "version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3", - "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3.tgz", - "integrity": "sha512-0CTnfEuUbLlO6n1fM89ERDbSwI4LoyZn+1OKVSwG+aVqohj34+mXRfwOWIM0ONtYtLGGBpddvQAnAZkg+cgS6g==" + "version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32.tgz", + "integrity": "sha512-HUCmkXAU2jqp2O1RvNtbE+seLGLyJGEABZS/R38rZjSAafAy0WzBuHq+tbZMnD+b5OSCsTVtIPVcuvx1ySxcWQ==" }, "node_modules/@sqltools/formatter": { "version": "1.2.5", @@ -392,6 +394,12 @@ "integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==", "dev": true }, + "node_modules/@types/chance": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@types/chance/-/chance-1.1.3.tgz", + "integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==", + "dev": true + }, "node_modules/@types/debug": { "version": "4.1.7", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz", @@ -665,6 +673,11 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/chance": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/chance/-/chance-1.1.9.tgz", + "integrity": "sha512-TfxnA/DcZXRTA4OekA2zL9GH8qscbbl6X0ZqU4tXhGveVY/mXWvEQLt5GwZcYXTEyEFflVtj+pG8nc8EwSm1RQ==" + }, "node_modules/character-entities": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", @@ -1897,13 +1910,13 @@ "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==" }, "node_modules/prisma": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.0.tgz", - "integrity": "sha512-TAnObUMGCM9NLt9nsRs1WWYQGPKsJOK8bN/7gSAnBcYIxMCFFDe+XtFYJbyTzsJZ/i+0rH4zg8au3m7HX354LA==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.1.tgz", + "integrity": "sha512-BR4itMCuzrDV4tn3e2TF+nh1zIX/RVU0isKtKoN28ADeoJ9nYaMhiuRRkFd2TZN8+l/XfYzoRKyHzUFXLQhmBQ==", "devOptional": true, "hasInstallScript": true, "dependencies": { - "@prisma/engines": "4.6.0" + "@prisma/engines": "4.6.1" }, "bin": { "prisma": "build/index.js", @@ -2863,23 +2876,23 @@ "peer": true }, "@prisma/client": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.0.tgz", - "integrity": "sha512-D9LaQinDxOHinRpcJTw2tjMtjhc9HTP+aF1IRd2oLldp/8TiwIfxK8x17OhBBiX4y1PzbJXXET7kS+5wB3es/w==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.1.tgz", + "integrity": "sha512-M1+NNrMzqaOIxT7PBGcTs3IZo7d1EW/+gVQd4C4gUgWBDGgD9AcIeZnUSidgWClmpMSgVUdnVORjsWWGUameYA==", "requires": { - "@prisma/engines-version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3" + "@prisma/engines-version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32" } }, "@prisma/engines": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.0.tgz", - "integrity": "sha512-S+72PAl0zTCbIGou1uXD/McvzdtP+bjOs0LRmGZfcOQcVqR9x/0f6Z+dqpUU0zIcqHEl+0DOB8UXaTwRvssFsQ==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.1.tgz", + "integrity": "sha512-3u2/XxvxB+Q7cMXHnKU0CpBiUK1QWqpgiBv28YDo1zOIJE3FCF8DI2vrp6vuwjGt5h0JGXDSvmSf4D4maVjJdw==", "devOptional": true }, "@prisma/engines-version": { - "version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3", - "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3.tgz", - "integrity": "sha512-0CTnfEuUbLlO6n1fM89ERDbSwI4LoyZn+1OKVSwG+aVqohj34+mXRfwOWIM0ONtYtLGGBpddvQAnAZkg+cgS6g==" + "version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32.tgz", + "integrity": "sha512-HUCmkXAU2jqp2O1RvNtbE+seLGLyJGEABZS/R38rZjSAafAy0WzBuHq+tbZMnD+b5OSCsTVtIPVcuvx1ySxcWQ==" }, "@sqltools/formatter": { "version": "1.2.5", @@ -2919,6 +2932,12 @@ "integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==", "dev": true }, + "@types/chance": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@types/chance/-/chance-1.1.3.tgz", + "integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==", + "dev": true + }, "@types/debug": { "version": "4.1.7", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz", @@ -3111,6 +3130,11 @@ "supports-color": "^7.1.0" } }, + "chance": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/chance/-/chance-1.1.9.tgz", + "integrity": "sha512-TfxnA/DcZXRTA4OekA2zL9GH8qscbbl6X0ZqU4tXhGveVY/mXWvEQLt5GwZcYXTEyEFflVtj+pG8nc8EwSm1RQ==" + }, "character-entities": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", @@ -3892,12 +3916,12 @@ "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==" }, "prisma": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.0.tgz", - "integrity": "sha512-TAnObUMGCM9NLt9nsRs1WWYQGPKsJOK8bN/7gSAnBcYIxMCFFDe+XtFYJbyTzsJZ/i+0rH4zg8au3m7HX354LA==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.1.tgz", + "integrity": "sha512-BR4itMCuzrDV4tn3e2TF+nh1zIX/RVU0isKtKoN28ADeoJ9nYaMhiuRRkFd2TZN8+l/XfYzoRKyHzUFXLQhmBQ==", "devOptional": true, "requires": { - "@prisma/engines": "4.6.0" + "@prisma/engines": "4.6.1" } }, "prop-types": { diff --git a/package.json b/package.json index f3c6726..81c633d 100644 --- a/package.json +++ b/package.json @@ -8,13 +8,15 @@ "scripts": { "dev": "next", "build": "next build", - "start": "next start" + "start": "next start", + "db": "npx prisma migrate reset --force" }, "dependencies": { "@hookform/resolvers": "^2.9.10", "@next-auth/prisma-adapter": "1.0.5", - "@prisma/client": "4.6.0", + "@prisma/client": "^4.6.1", "bootstrap": "^5.2.2", + "chance": "^1.1.9", "next": "13.0.2", "next-auth": "4.16.4", "react": "18.2.0", @@ -24,10 +26,11 @@ "yup": "^0.32.11" }, "devDependencies": { + "@types/chance": "^1.1.3", "@types/next-auth": "3.13.0", "@types/node": "18.11.9", "@types/react": "18.0.25", - "prisma": "4.6.0", + "prisma": "^4.6.1", "ts-node": "10.9.1", "typescript": "4.8.4" }, diff --git a/pages/api/gain/index.ts b/pages/api/gain/index.ts new file mode 100644 index 0000000..69fcb91 --- /dev/null +++ b/pages/api/gain/index.ts @@ -0,0 +1,107 @@ +import prisma from '../../../lib/prisma'; +import chance from 'chance' + +import { NextApiRequest, NextApiResponse } from 'next'; +import { getSession } from 'next-auth/react'; +import { Cadeaux } from '../../../enum/cadeaux.enum'; +import { Role } from '../../../enum/role.enum'; + + + +//API gain qui va generer un code cadeau qui sera sur la facture du client +//On part du principe qu'une 'API caisse'(qu'on ne gere pas) déclenche l'appel à l'API gain + +export default async function generationGain(req: NextApiRequest, res: NextApiResponse) { + const session = await getSession({ req }) + + //récuperation des tickets disponible + const getTickets = await prisma.ticketsRestants.findFirst({ + where: { + id: 1 + }, + }) + + const { total } = getTickets; + const isTicketsAvaible = total > 0; + + //récupération des informations de l'utilisateur connecté + const getCurrentUser = await prisma.user.findMany({ + where: { email: session.user.email }, + }) + + //récupération du role + const { role } = getCurrentUser[0]; + const isAdmin = role === Role.ADMIN; + const isSuperAdmin = Role.SUPERADMIN; + + if (session && isTicketsAvaible) { + if (isAdmin || isSuperAdmin) { + + //creation d'un numéro de gain aléatoire + const gainNumber = (Math.random() + 1).toString(36).substring(7).toUpperCase() + + //création d'un id de produit de façon pondérée + let weightedRandomGainId = chance().weighted([ + Cadeaux.CoffretDecouvert69, + Cadeaux.CoffretDecouvert39, + Cadeaux.TheSignature, + Cadeaux.TheDetox, + Cadeaux.Infuseur], + [4, 6, 10, 20, 60]); + + //création d'un gain + const gainCreated = await prisma.gain.create({ + data: { + codeCadeau: gainNumber, + } + }) + + //mise à jour du gain avec l'id de produit pondéré + const gainResult = await prisma.gain.update({ + where: { id: gainCreated.id }, + data: { + produitId: weightedRandomGainId, + } + }) + + //on retire 1 ticket + await prisma.ticketsRestants.update({ + where: { + id: getTickets.id + }, + data: { + total: { + decrement: 1 + } + } + }) + res.status(200).send({ message: 'Gain has been generated !', result: gainResult }); + } + } else { + res.status(401).send({ message: 'Unauthorized' }) + } + +} + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pages/api/profile/index.ts b/pages/api/profile/index.ts index 210f66a..c89e344 100644 --- a/pages/api/profile/index.ts +++ b/pages/api/profile/index.ts @@ -7,6 +7,7 @@ import { getSession } from 'next-auth/react' // Required fields in body: title export default async function handle(req: NextApiRequest, res: NextApiResponse) { const { bioValue } = req.body; + console.log('server biovalue:', bioValue) const session = await getSession({ req }); if (req.method === "PUT") { diff --git a/pages/api/superadmin/index.ts b/pages/api/superadmin/index.ts new file mode 100644 index 0000000..5feae3f --- /dev/null +++ b/pages/api/superadmin/index.ts @@ -0,0 +1,36 @@ + +import { NextApiRequest, NextApiResponse } from 'next'; +import { getSession } from 'next-auth/react'; +import { Role } from '../../../enum/role.enum'; +import prisma from '../../../lib/prisma'; + + +//api qui va rendre un utilisateur super admin (pour les developpeurs) +//--> http://localhost:3000/api/superadmin?pass=1234 (a effacer) + +export default async function makeMeSuper(req: NextApiRequest, res: NextApiResponse) { + const { pass } = req.query; + const session = await getSession({ req }) + const goodPassword = pass === '1234'; + + //si utilisateur connecté et que le parametre 'pass' est '1234' + if (session && goodPassword) { + + //MAJ de l'utilisateur en superadmin + await prisma.user.update({ + where: { email: session.user.email }, + data: { + role: Role.SUPERADMIN, + }, + }) + return res.status(200).send({ message: 'Profiled updated welcome SUPERADMIN !' }); + } else { + res.status(401).send({ message: 'Unauthorized' }) + } +} + + + + + + diff --git a/pages/index.tsx b/pages/index.tsx index 6fd23d2..f7419e2 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -1,60 +1,87 @@ import React from "react"; -import type { GetServerSideProps } from "next"; import Layout from "../components/Layout"; -import Post, { PostProps } from "../components/Post"; import prisma from '../lib/prisma' -export const getServerSideProps: GetServerSideProps = async () => { - const feed = await prisma.post.findMany({ - where: { - published: true, - }, - include: { - author: { - select: { - name: true, - }, - }, - }, +import { yupResolver } from "@hookform/resolvers/yup"; +import { useForm } from "react-hook-form"; +import * as Yup from 'yup'; +import { useSession } from "next-auth/react"; + +type CodeSubmitForm = { + codeCadeau: string; +}; + +const MainPage = () => { + const { data: session } = useSession(); + + const validationSchema = Yup.object().shape({ + codeCadeau: Yup.string().trim().required("Vous n'avez pas rentrer de code cadeau !"), }); - return { - props: { feed }, + + const { + register, + handleSubmit, + formState: { errors } + } = useForm({ + resolver: yupResolver(validationSchema) + }); + + const onSubmit = async (data: CodeSubmitForm) => { + + if (!session) { + return +

Vous devez vous connecter pour tester votre !

+
+ } + + + + // try { + // const body = { bioValue: data.bio }; + // await fetch(`/api/profile`, { + // method: "POST", + // headers: { "Content-Type": "application/json" }, + // body: JSON.stringify(body), + // }) + // .then((res) => res.json()) + // .then((data) => { + // setResponse(data); + // console.log('response', data); + // }) + // await Router.push("/profile"); + // } catch (error) { + // console.error(error); + // } }; -}; -type Props = { - feed: PostProps[]; -}; -const Blog = (props : Props) => { + return (
-

Public Feed

+

TheTipTop - jeu concours !

- {props.feed.map((post) => ( -
- +
+
+ + +
{errors.codeCadeau?.message}
+
+
+
- ))} +
-
); }; -export default Blog; +export default MainPage; diff --git a/pages/profile.tsx b/pages/profile.tsx index cee0546..8d180d7 100644 --- a/pages/profile.tsx +++ b/pages/profile.tsx @@ -3,30 +3,54 @@ import { GetServerSideProps } from "next"; import Layout from "../components/Layout"; import { useSession, getSession } from "next-auth/react"; import prisma from '../lib/prisma' -import Image from "next/image"; import Router from "next/router"; import { ProfileProps } from "../types/profile"; -import { Resolver, SubmitHandler, useForm } from "react-hook-form"; +import { Resolver, SubmitHandler } from "react-hook-form"; +//https://www.bezkoder.com/react-hook-form-typescript/ + +import { useForm } from 'react-hook-form'; +import { yupResolver } from '@hookform/resolvers/yup'; +import * as Yup from 'yup'; + +type UserSubmitForm = { + bio: string; +}; + +type Profil = { + isUserProfile: any; +} + +interface ResponseData { + result: string; + message: string +} + export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { const session = await getSession({ req }); + //pas de session ? on ne retourne un code erreur + //voir pour rediriger vers la page de connection + //ou afficher pop up "vous n'est pas connecter" if (!session) { res.statusCode = 403; return { props: { profile: null } }; } - // si profil ? on retour le Profil + // si session ? on récupére le profil de l'utilisateur si il existe if (session) { const isUserProfile = await prisma.profile.findMany({ where: { user: { email: session.user.email }, } }) + console.log('profil utilisateur ?', isUserProfile); - if (!isUserProfile) { - const createProfile = await prisma.profile.create({ + + // il n'existe pas ? on le crée + if (isUserProfile.length <= 0) { + const newProfil = await prisma.profile.create({ data: { bio: "", user: { @@ -34,48 +58,40 @@ export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { }, }, }); - return { props: { createProfile } }; + console.log('newProfil', newProfil); + } + // on renvoi le profil return { props: { isUserProfile } }; } }; -// type Props = { -// profile: any; -// }; - -interface ResponseData { - result: string; - message: string -} - -type FormValues = { - bio: string; -}; - +const Profil = ({ isUserProfile }: Profil) => { + const validationSchema = Yup.object().shape({ + bio: Yup.string().trim().required("ce champ ne peux etre vide..."), + }); + const { + register, + handleSubmit, + reset, + formState: { errors } + } = useForm({ + resolver: yupResolver(validationSchema) + }); - -const Profil = (props: any) => { - const { register, handleSubmit, formState: { errors } } = useForm({ resolver }); - - - const [bio, setBio] = useState(props.isUserProfile[0].bio || ""); const [response, setResponse] = useState(); const { data: session } = useSession(); React.useEffect(() => { - console.log('user profil', props.isUserProfile) + console.log('user profil props', isUserProfile) }, []) - - const onSubmit: SubmitHandler = async (data) => { - - console.log('input value', data.bio); - setBio(data.bio) + const onSubmit = async (data: UserSubmitForm) => { + console.log(data); try { const body = { bioValue: data.bio }; @@ -89,8 +105,6 @@ const Profil = (props: any) => { setResponse(data); console.log('response', data); }) - - await Router.push("/profile"); } catch (error) { console.error(error); @@ -111,36 +125,47 @@ const Profil = (props: any) => {

Mon compte

-
-

Ma bio : {bio}

- - -
+ +
+

Ma bio : {isUserProfile[0]?.bio}

+
+
+ + +
{errors.bio?.message}
+
+ + +
+ + +
+
+
+ +

Email : {session.user.email}

{response &&

{response.message}

}
- ); }; + + export default Profil; diff --git a/prisma/dev.db b/prisma/dev.db deleted file mode 100644 index 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C|T0TWG>3k7nfA~LM>*vi;IZV2{*bLQ>&*Mda3Z?h+{%BntA{4{^LiB z&-cAMo@dAC&j2>FB6?zBteA_hkFH1P+j6^w#pf???0B9Y+R}n1ZN zXW#xCh|Q>>%c^L9+>(6cNItT!|2f00e*l5C8%|00;m9An=wF_(k7)tp5vUgjrnwf945% z_Lf!<%mxBL00;m9AOHk_01yBIKmZ5;0U+=dCh!e!#s83L0PO33U*J2Qzz+l83H)W? zAHTxLpz1&X2mk>f00e*l5C8%|00;m9AOHk@?gXBBKfqoyO@Z&J_ZYh~ZGiXd-a~AC zhJcN)dtdr*%>`gz|HJtIpSyd(03ZMafB+Bx0zd!=00AHX1b_e#00KW#0&xBRGsO$a zfdCKy0zd!=00AHX1b_e#00KY&2)q#l?D_w(z<+tr3l<;%1b_e#00KY&2mk>f00e*l z5C8%|;LAc_5A%7RV+Q)yLs1s{zQz21|Kkau*O#S=P!Avg1b_e#00KY&2mk>f00e*l Q5C8%|;F^HXi}`*32O;GqKL7v# diff --git a/prisma/migrations/20221109202932_init/migration.sql b/prisma/migrations/20221109202932_init/migration.sql deleted file mode 100644 index f5d98e8..0000000 --- a/prisma/migrations/20221109202932_init/migration.sql +++ /dev/null @@ -1,70 +0,0 @@ --- CreateTable -CREATE TABLE "Post" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "title" TEXT NOT NULL, - "content" TEXT, - "published" BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER, - CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE -); - --- CreateTable -CREATE TABLE "accounts" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "user_id" INTEGER NOT NULL, - "type" TEXT NOT NULL, - "provider" TEXT NOT NULL, - "provider_account_id" TEXT NOT NULL, - "refresh_token" TEXT, - "access_token" TEXT, - "expires_at" INTEGER, - "token_type" TEXT, - "scope" TEXT, - "id_token" TEXT, - "session_state" TEXT, - "oauth_token_secret" TEXT, - "oauth_token" TEXT, - CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE -); - --- CreateTable -CREATE TABLE "sessions" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "session_token" TEXT NOT NULL, - "user_id" INTEGER NOT NULL, - "expires" DATETIME NOT NULL, - CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE -); - --- CreateTable -CREATE TABLE "users" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "name" TEXT, - "email" TEXT, - "email_verified" DATETIME, - "image" TEXT, - "created_at" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updated_at" DATETIME NOT NULL -); - --- CreateTable -CREATE TABLE "verificationtokens" ( - "identifier" TEXT NOT NULL, - "token" TEXT NOT NULL, - "expires" DATETIME NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "accounts_provider_provider_account_id_key" ON "accounts"("provider", "provider_account_id"); - --- CreateIndex -CREATE UNIQUE INDEX "sessions_session_token_key" ON "sessions"("session_token"); - --- CreateIndex -CREATE UNIQUE INDEX "users_email_key" ON "users"("email"); - --- CreateIndex -CREATE UNIQUE INDEX "verificationtokens_token_key" ON "verificationtokens"("token"); - --- CreateIndex -CREATE UNIQUE INDEX "verificationtokens_identifier_token_key" ON "verificationtokens"("identifier", "token"); diff --git a/prisma/migrations/20221110093840_/migration.sql b/prisma/migrations/20221110093840_/migration.sql deleted file mode 100644 index 276bf9b..0000000 --- a/prisma/migrations/20221110093840_/migration.sql +++ /dev/null @@ -1,10 +0,0 @@ --- CreateTable -CREATE TABLE "Profile" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "bio" TEXT, - "userId" INTEGER NOT NULL, - CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE -); - --- CreateIndex -CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); diff --git a/prisma/migrations/20221110112827_/migration.sql b/prisma/migrations/20221110112827_/migration.sql deleted file mode 100644 index ed4acf4..0000000 --- a/prisma/migrations/20221110112827_/migration.sql +++ /dev/null @@ -1,21 +0,0 @@ -/* - Warnings: - - - You are about to drop the `Profile` table. If the table is not empty, all the data it contains will be lost. - -*/ --- DropTable -PRAGMA foreign_keys=off; -DROP TABLE "Profile"; -PRAGMA foreign_keys=on; - --- CreateTable -CREATE TABLE "Profil" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "bio" TEXT, - "userId" INTEGER NOT NULL, - CONSTRAINT "Profil_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE -); - --- CreateIndex -CREATE UNIQUE INDEX "Profil_userId_key" ON "Profil"("userId"); diff --git a/prisma/migrations/20221110113201_/migration.sql b/prisma/migrations/20221110113201_/migration.sql deleted file mode 100644 index 25b5ab9..0000000 --- a/prisma/migrations/20221110113201_/migration.sql +++ /dev/null @@ -1,21 +0,0 @@ -/* - Warnings: - - - You are about to drop the `Profil` table. If the table is not empty, all the data it contains will be lost. - -*/ --- DropTable -PRAGMA foreign_keys=off; -DROP TABLE "Profil"; -PRAGMA foreign_keys=on; - --- CreateTable -CREATE TABLE "Profile" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "bio" TEXT, - "userId" INTEGER NOT NULL, - CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE -); - --- CreateIndex -CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); diff --git a/prisma/migrations/20221112185745_/migration.sql b/prisma/migrations/20221112185745_/migration.sql new file mode 100644 index 0000000..f16599d --- /dev/null +++ b/prisma/migrations/20221112185745_/migration.sql @@ -0,0 +1,144 @@ +-- CreateEnum +CREATE TYPE "Role" AS ENUM ('USER', 'ADMIN', 'SUPERADMIN'); + +-- CreateTable +CREATE TABLE "accounts" ( + "id" SERIAL NOT NULL, + "user_id" INTEGER NOT NULL, + "type" TEXT NOT NULL, + "provider" TEXT NOT NULL, + "provider_account_id" TEXT NOT NULL, + "refresh_token" TEXT, + "access_token" TEXT, + "expires_at" INTEGER, + "token_type" TEXT, + "scope" TEXT, + "id_token" TEXT, + "session_state" TEXT, + "oauth_token_secret" TEXT, + "oauth_token" TEXT, + + CONSTRAINT "accounts_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "sessions" ( + "id" SERIAL NOT NULL, + "session_token" TEXT NOT NULL, + "user_id" INTEGER NOT NULL, + "expires" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "sessions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "users" ( + "id" SERIAL NOT NULL, + "name" TEXT, + "email" TEXT, + "email_verified" TIMESTAMP(3), + "image" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + "role" "Role" NOT NULL DEFAULT 'USER', + + CONSTRAINT "users_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Post" ( + "id" SERIAL NOT NULL, + "title" TEXT NOT NULL, + "content" TEXT, + "published" BOOLEAN NOT NULL DEFAULT false, + "authorId" INTEGER, + + CONSTRAINT "Post_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Profile" ( + "id" SERIAL NOT NULL, + "bio" TEXT, + "userId" INTEGER NOT NULL, + + CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "TicketsRestants" ( + "id" SERIAL NOT NULL, + "total" INTEGER NOT NULL, + + CONSTRAINT "TicketsRestants_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Gain" ( + "id" SERIAL NOT NULL, + "codeCadeau" TEXT NOT NULL, + "dateRetrait" TIMESTAMP(3), + "produitId" INTEGER, + "userId" INTEGER, + + CONSTRAINT "Gain_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Produit" ( + "id" SERIAL NOT NULL, + "actif" BOOLEAN, + "nomProduit" TEXT, + "prixTtc" DECIMAL(65,30), + + CONSTRAINT "Produit_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "verificationtokens" ( + "identifier" TEXT NOT NULL, + "token" TEXT NOT NULL, + "expires" TIMESTAMP(3) NOT NULL +); + +-- CreateIndex +CREATE UNIQUE INDEX "accounts_provider_provider_account_id_key" ON "accounts"("provider", "provider_account_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "sessions_session_token_key" ON "sessions"("session_token"); + +-- CreateIndex +CREATE UNIQUE INDEX "users_email_key" ON "users"("email"); + +-- CreateIndex +CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Gain_codeCadeau_key" ON "Gain"("codeCadeau"); + +-- CreateIndex +CREATE UNIQUE INDEX "Gain_userId_key" ON "Gain"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "verificationtokens_token_key" ON "verificationtokens"("token"); + +-- CreateIndex +CREATE UNIQUE INDEX "verificationtokens_identifier_token_key" ON "verificationtokens"("identifier", "token"); + +-- AddForeignKey +ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Gain" ADD CONSTRAINT "Gain_produitId_fkey" FOREIGN KEY ("produitId") REFERENCES "Produit"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Gain" ADD CONSTRAINT "Gain_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml index e5e5c47..fbffa92 100644 --- a/prisma/migrations/migration_lock.toml +++ b/prisma/migrations/migration_lock.toml @@ -1,3 +1,3 @@ # Please do not edit this file manually # It should be added in your version-control system (i.e. Git) -provider = "sqlite" \ No newline at end of file +provider = "postgresql" \ No newline at end of file diff --git a/prisma/schema.prisma b/prisma/schema.prisma index cbbd836..9525ee7 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -3,8 +3,8 @@ generator client { } datasource db { - provider = "sqlite" - url = "file:./dev.db" + provider = "postgresql" + url = env("DATABASE_URL") } model Account { @@ -51,6 +51,8 @@ model User { accounts Account[] sessions Session[] profile Profile? + gain Gain? + role Role @default(USER) @@map(name: "users") } @@ -71,6 +73,35 @@ model Profile { userId Int @unique } +model TicketsRestants { + id Int @id @default(autoincrement()) + total Int +} + +model Gain { + id Int @id @default(autoincrement()) + codeCadeau String @unique + dateRetrait DateTime? + produit Produit? @relation(fields: [produitId], references: [id]) + produitId Int? + user User? @relation(fields: [userId], references: [id]) + userId Int? @unique +} + +model Produit { + id Int @id @default(autoincrement()) + actif Boolean? + nomProduit String? + prixTtc Decimal? + refGain Gain[] +} + +enum Role { + USER + ADMIN + SUPERADMIN +} + model VerificationToken { identifier String token String @unique diff --git a/prisma/seed.ts b/prisma/seed.ts index ea8ab56..7433459 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,64 +1,50 @@ -import { PrismaClient, Prisma } from '@prisma/client' +// import prisma from '../lib/prisma' +import { PrismaClient } from '@prisma/client' +import { generateGains } from './seed/gains' +import { produitsData } from './seed/produits' +// import { userData } from './seed/user' -const prisma = new PrismaClient() - -const userData: Prisma.UserCreateInput[] = [ - { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: [ - { - title: 'Join the Prisma Slack', - content: 'https://slack.prisma.io', - published: true, - }, - ], - }, - }, - { - name: 'Nilu', - email: 'nilu@prisma.io', - posts: { - create: [ - { - title: 'Follow Prisma on Twitter', - content: 'https://www.twitter.com/prisma', - published: true, - }, - ], - }, - }, - { - name: 'Mahmoud', - email: 'mahmoud@prisma.io', - posts: { - create: [ - { - title: 'Ask a question about Prisma on GitHub', - content: 'https://www.github.com/prisma/prisma/discussions', - published: true, - }, - { - title: 'Prisma on YouTube', - content: 'https://pris.ly/youtube', - }, - ], - }, - }, -] +const prisma = new PrismaClient(); async function main() { console.log(`Start seeding ...`) - for (const u of userData) { - const user = await prisma.user.create({ - data: u, + + //création des tickets restants + const tickets = await prisma.ticketsRestants.create({ + data: { + total: 1500000 + }, + }) + console.log(`Created ticket: ${tickets.total}`) + + + //création des produits + for (const p of produitsData) { + const produit = await prisma.produit.create({ + data: p, }) - console.log(`Created user with id: ${user.id}`) + console.log(`Created produit: ${produit.nomProduit}`) } + + ///////////////////////////////////////////////////// + + //création des utilisateurs + // for (const u of userData) { + // const user = await prisma.user.create({ + // data: u, + // }) + // console.log(`Created user with id: ${user.id}`) + // } + + //création de 5 gains + for (let i = 1; i <= 5; i++) { + await generateGains(); + } + console.log(`Seeding finished.`) } + main() .then(async () => { await prisma.$disconnect() diff --git a/prisma/seed/gains.ts b/prisma/seed/gains.ts new file mode 100644 index 0000000..a64f58d --- /dev/null +++ b/prisma/seed/gains.ts @@ -0,0 +1,48 @@ +// import { produits } from './produits'; +import prisma from '../../lib/prisma' +import { Chance } from 'chance' +import { Cadeaux } from '../../enum/cadeaux.enum'; +let chance = new Chance(); + +export const generateGains = async () => { + //génération d'un code cadeau + const randomNoGain = (Math.random() + 1).toString(36).substring(7).toUpperCase() + + //création d'un gain + const gainCreated = await prisma.gain.create({ + data: { + codeCadeau: randomNoGain, + } + }) + + //crétion d'un id de produit de façon pondérée + let weightedRandomGain = chance.weighted([ + Cadeaux.CoffretDecouvert69, + Cadeaux.CoffretDecouvert39, + Cadeaux.TheSignature, + Cadeaux.TheDetox, + Cadeaux.Infuseur], + [4, 6, 10, 20, 60]); + + //mise à jour du gain avec l'id de produit pondéré + const gainUpdated = await prisma.gain.update({ + where: { id: gainCreated.id }, + data: { + produitId: weightedRandomGain, + } + }) + //on retire 1 ticket + await prisma.ticketsRestants.update({ + where: { + id: 1 + }, + data: { + total: { + decrement: 1 + } + } + }) + + console.log(`Created gain ! : ${gainUpdated.codeCadeau}`) +} + diff --git a/prisma/seed/produits.ts b/prisma/seed/produits.ts new file mode 100644 index 0000000..1847a05 --- /dev/null +++ b/prisma/seed/produits.ts @@ -0,0 +1,24 @@ +import { Prisma } from "@prisma/client"; + +export const produitsData: Prisma.ProduitCreateInput[] = [ + { + nomProduit: 'coffret découverte à 69€', + prixTtc: 69, + + }, + { + nomProduit: 'coffret découverte à 39€', + prixTtc: 39, + }, + { + nomProduit: 'thé signature', + prixTtc: 10, + }, + { + nomProduit: 'thé détox ou infusion', + prixTtc: 6, + }, + { + nomProduit: 'infuseur à thé', + prixTtc: 3, + }] diff --git a/prisma/seed/user.ts b/prisma/seed/user.ts new file mode 100644 index 0000000..bc9c26e --- /dev/null +++ b/prisma/seed/user.ts @@ -0,0 +1,47 @@ +import { Prisma } from "@prisma/client"; + +export const userData: Prisma.UserCreateInput[] = [ + { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: [ + { + title: 'Join the Prisma Slack', + content: 'https://slack.prisma.io', + published: true, + }, + ], + }, + }, + { + name: 'Nilu', + email: 'nilu@prisma.io', + posts: { + create: [ + { + title: 'Follow Prisma on Twitter', + content: 'https://www.twitter.com/prisma', + published: true, + }, + ], + }, + }, + { + name: 'Mahmoud', + email: 'mahmoud@prisma.io', + posts: { + create: [ + { + title: 'Ask a question about Prisma on GitHub', + content: 'https://www.github.com/prisma/prisma/discussions', + published: true, + }, + { + title: 'Prisma on YouTube', + content: 'https://pris.ly/youtube', + }, + ], + }, + }, +] \ No newline at end of file