⚡️ ⚡️ add - ajout d'une page mon compte connecter a la bdd + API + routes
This commit is contained in:
1 parent
ae437a097b
commit
38159b90c1
12 files changed
+303
-16
No files matched your search
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Next.js: debug server-side",
|
||||
"type": "node-terminal",
|
||||
"request": "launch",
|
||||
"command": "npm run dev"
|
||||
},
|
||||
{
|
||||
"name": "Next.js: debug client-side",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"url": "http://localhost:3000"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Launch Program",
|
||||
"skipFiles": [
|
||||
"<node_internals>/**"
|
||||
],
|
||||
"program": "${workspaceFolder}\\pages\\moncompte.tsx",
|
||||
"outFiles": [
|
||||
"${workspaceFolder}/**/*.js"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -8,7 +8,7 @@ const Header = () => {
|
||||
const isActive: (pathname: string) => boolean = (pathname) =>
|
||||
router.pathname === pathname;
|
||||
|
||||
const {data: session, status} = useSession();
|
||||
const { data: session, status } = useSession();
|
||||
|
||||
let left = (
|
||||
<div className="left">
|
||||
@@ -124,6 +124,11 @@ const Header = () => {
|
||||
<Link href="/drafts" legacyBehavior>
|
||||
<a data-active={isActive("/drafts")}>My drafts</a>
|
||||
</Link>
|
||||
<Link href="/profile" legacyBehavior>
|
||||
<a data-active={isActive("/profile")}>
|
||||
Mon Compte
|
||||
</a>
|
||||
</Link>
|
||||
<style jsx>{`
|
||||
.bold {
|
||||
font-weight: bold;
|
||||
|
||||
@@ -16,12 +16,12 @@ const options = {
|
||||
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
authorization: 'https://accounts.google.com/o/oauth2/v2/auth?prompt=consent&access_type=offline&response_type=code',
|
||||
}),
|
||||
EmailProvider({
|
||||
server: process.env.EMAIL_SERVER,
|
||||
from: process.env.EMAIL_FROM,
|
||||
}),
|
||||
}),
|
||||
EmailProvider({
|
||||
server: process.env.EMAIL_SERVER,
|
||||
from: process.env.EMAIL_FROM,
|
||||
}),
|
||||
],
|
||||
adapter: PrismaAdapter(prisma),
|
||||
secret: process.env.SECRET,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import prisma from '../../../lib/prisma'
|
||||
import { getSession } from 'next-auth/react'
|
||||
|
||||
|
||||
// UPDATE /api/profile
|
||||
// Required fields in body: title
|
||||
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { bioValue } = req.body;
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (req.method === "PUT") {
|
||||
if (session) {
|
||||
const updateUserProfil = await prisma.user.update({
|
||||
where: { email: session.user.email },
|
||||
data: {
|
||||
profile: {
|
||||
update: {
|
||||
bio: bioValue,
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
res.status(200).send({ result: updateUserProfil, message: 'Profiled updated !' });
|
||||
} else {
|
||||
res.status(401).send({ message: 'Unauthorized' })
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
`The HTTP ${req.method} method is not supported at this route.`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import React, { useState } from "react";
|
||||
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";
|
||||
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session) {
|
||||
res.statusCode = 403;
|
||||
return { props: { profile: null } };
|
||||
}
|
||||
// si profil ? on retour le Profil
|
||||
|
||||
if (session) {
|
||||
const isUserProfile = await prisma.profile.findMany({
|
||||
where: {
|
||||
user: { email: session.user.email },
|
||||
}
|
||||
})
|
||||
|
||||
if (!isUserProfile) {
|
||||
const createProfile = await prisma.profile.create({
|
||||
data: {
|
||||
bio: "",
|
||||
user: {
|
||||
connect: { email: session.user.email },
|
||||
},
|
||||
},
|
||||
});
|
||||
return { props: { createProfile } };
|
||||
}
|
||||
|
||||
return { props: { isUserProfile } };
|
||||
}
|
||||
};
|
||||
|
||||
// type Props = {
|
||||
// profile: any;
|
||||
// };
|
||||
|
||||
interface ResponseData {
|
||||
result: string;
|
||||
message: string
|
||||
}
|
||||
|
||||
|
||||
const Profil = (props: any) => {
|
||||
const [bio, setBio] = useState(props.isUserProfile[0].bio || "");
|
||||
const [response, setResponse] = useState<ResponseData | undefined>();
|
||||
const { data: session } = useSession();
|
||||
|
||||
React.useEffect(() => {
|
||||
console.log('user profil', props.isUserProfile)
|
||||
}, [])
|
||||
|
||||
|
||||
|
||||
|
||||
const submitData = async (e: React.SyntheticEvent) => {
|
||||
e.preventDefault();
|
||||
console.log('input value', e.target[0].value);
|
||||
setBio(e.target[0].value)
|
||||
|
||||
try {
|
||||
const body = { bioValue: e.target[0].value };
|
||||
await fetch(`/api/profile`, {
|
||||
method: "PUT",
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<Layout>
|
||||
<h1>Mon Compte</h1>
|
||||
<div>Vous devez être authentifié pour voir cette page.</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="page">
|
||||
<h1>Mon compte</h1>
|
||||
<main>
|
||||
<form onSubmit={submitData}>
|
||||
<p>Ma bio : {bio}</p>
|
||||
<input
|
||||
autoFocus
|
||||
placeholder="Ma bio..."
|
||||
type="text"
|
||||
defaultValue={bio}
|
||||
/>
|
||||
<input type="submit" value="Save changes" />
|
||||
</form>
|
||||
<p>Email : {session.user.email}</p>
|
||||
{response && <p>{response.message}</p>}
|
||||
</main>
|
||||
</div>
|
||||
<style jsx>{`
|
||||
.post {
|
||||
background: white;
|
||||
transition: box-shadow 0.1s ease-in;
|
||||
}
|
||||
|
||||
.post:hover {
|
||||
box-shadow: 1px 1px 3px #aaa;
|
||||
}
|
||||
|
||||
.post + .post {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
`}</style>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default Profil;
|
||||
Binary file not shown.
@@ -0,0 +1,10 @@
|
||||
-- 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");
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
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");
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
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");
|
||||
+17
-9
@@ -7,15 +7,6 @@ datasource db {
|
||||
url = "file:./dev.db"
|
||||
}
|
||||
|
||||
model Post {
|
||||
id Int @id @default(autoincrement())
|
||||
title String
|
||||
content String?
|
||||
published Boolean @default(false)
|
||||
author User? @relation(fields: [authorId], references: [id])
|
||||
authorId Int?
|
||||
}
|
||||
|
||||
model Account {
|
||||
id Int @id @default(autoincrement())
|
||||
userId Int @map("user_id")
|
||||
@@ -59,10 +50,27 @@ model User {
|
||||
posts Post[]
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
profile Profile?
|
||||
|
||||
@@map(name: "users")
|
||||
}
|
||||
|
||||
model Post {
|
||||
id Int @id @default(autoincrement())
|
||||
title String
|
||||
content String?
|
||||
published Boolean @default(false)
|
||||
author User? @relation(fields: [authorId], references: [id])
|
||||
authorId Int?
|
||||
}
|
||||
|
||||
model Profile {
|
||||
id Int @id @default(autoincrement())
|
||||
bio String?
|
||||
user User? @relation(fields: [userId], references: [id])
|
||||
userId Int @unique
|
||||
}
|
||||
|
||||
model VerificationToken {
|
||||
identifier String
|
||||
token String @unique
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
export type PostProps = {
|
||||
id: number;
|
||||
title: string;
|
||||
author: {
|
||||
name: string;
|
||||
email: string;
|
||||
} | null;
|
||||
content: string;
|
||||
published: boolean;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
export type ProfileProps = {
|
||||
id: number;
|
||||
bio: string;
|
||||
user: {
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user