parent
e066b631e1
commit
b19d1c2efe
@ -1,2 +1,7 @@
|
||||
{
|
||||
"workbench.colorCustomizations": {
|
||||
"activityBar.background": "#4C1F25",
|
||||
"titleBar.activeBackground": "#6A2C34",
|
||||
"titleBar.activeForeground": "#FEFCFC"
|
||||
}
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { getSession } from 'next-auth/react';
|
||||
import prisma from '../../../../lib/prisma'
|
||||
|
||||
|
||||
// DELETE /api/post/:id
|
||||
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
|
||||
const postId = req.query.id;
|
||||
|
||||
const session = await getSession({ req })
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
if (session) {
|
||||
const post = await prisma.post.delete({
|
||||
where: { id: Number(postId) },
|
||||
});
|
||||
res.json(post);
|
||||
} else {
|
||||
res.status(401).send({ message: 'Unauthorized' })
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
`The HTTP ${req.method} method is not supported at this route.`
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import prisma from '../../../../lib/prisma'
|
||||
import { getSession } from 'next-auth/react'
|
||||
|
||||
|
||||
// POST /api/post
|
||||
// Required fields in body: title
|
||||
// Optional fields in body: content
|
||||
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { title, content } = req.body;
|
||||
|
||||
const session = await getSession({ req });
|
||||
if (session) {
|
||||
const result = await prisma.post.create({
|
||||
data: {
|
||||
title: title,
|
||||
content: content,
|
||||
author: { connect: { email: session?.user?.email } },
|
||||
},
|
||||
});
|
||||
res.json(result);
|
||||
} else {
|
||||
res.status(401).send({ message: 'Unauthorized' })
|
||||
}
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
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;
|
||||
console.log('server biovalue:', bioValue)
|
||||
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.`
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { getSession } from 'next-auth/react';
|
||||
import prisma from '../../../../lib/prisma'
|
||||
|
||||
// PUT /api/publish/:id
|
||||
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
|
||||
const postId = req.query.id;
|
||||
const session = await getSession({ req })
|
||||
|
||||
if (session) {
|
||||
const post = await prisma.post.update({
|
||||
where: { id: Number(postId) },
|
||||
data: { published: true },
|
||||
});
|
||||
res.json(post);
|
||||
} else {
|
||||
res.status(401).send({ message: 'Unauthorized' })
|
||||
}
|
||||
}
|
||||
@ -1,81 +0,0 @@
|
||||
import React, { useState } from "react";
|
||||
import Layout from "../../components/Layout";
|
||||
import Router from "next/router";
|
||||
|
||||
const Draft = () => {
|
||||
const [title, setTitle] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
|
||||
const submitData = async (e: React.SyntheticEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const body = { title, content };
|
||||
await fetch(`/api/post`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
await Router.push("/drafts");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div>
|
||||
<form onSubmit={submitData}>
|
||||
<h1>New Draft</h1>
|
||||
<input
|
||||
autoFocus
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Title"
|
||||
type="text"
|
||||
value={title}
|
||||
/>
|
||||
<textarea
|
||||
cols={50}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder="Content"
|
||||
rows={8}
|
||||
value={content}
|
||||
/>
|
||||
<input disabled={!content || !title} type="submit" value="Create" />
|
||||
<a className="back" href="#" onClick={() => Router.push("/")}>
|
||||
or Cancel
|
||||
</a>
|
||||
</form>
|
||||
</div>
|
||||
<style jsx>{`
|
||||
.page {
|
||||
background: white;
|
||||
padding: 3rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
margin: 0.5rem 0;
|
||||
border-radius: 0.25rem;
|
||||
border: 0.125rem solid rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
input[type="submit"] {
|
||||
background: #ececec;
|
||||
border: 0;
|
||||
padding: 1rem 2rem;
|
||||
}
|
||||
|
||||
.back {
|
||||
margin-left: 1rem;
|
||||
}
|
||||
`}</style>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default Draft;
|
||||
@ -1,78 +0,0 @@
|
||||
import React from "react";
|
||||
import { GetServerSideProps } from "next";
|
||||
import Layout from "../../components/Layout";
|
||||
import Post, { PostProps } from "../../components/Post";
|
||||
import { useSession, getSession } from "next-auth/react";
|
||||
import prisma from '../../lib/prisma'
|
||||
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
|
||||
const session = await getSession({ req });
|
||||
if (!session) {
|
||||
res.statusCode = 403;
|
||||
return { props: { drafts: [] } };
|
||||
}
|
||||
|
||||
const drafts = await prisma.post.findMany({
|
||||
where: {
|
||||
author: { email: session.user.email },
|
||||
published: false,
|
||||
},
|
||||
include: {
|
||||
author: {
|
||||
select: { name: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
props: { drafts },
|
||||
};
|
||||
};
|
||||
|
||||
type Props = {
|
||||
drafts: PostProps[];
|
||||
};
|
||||
|
||||
const Drafts = (props: Props) => {
|
||||
const { data: session } = useSession();
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<Layout>
|
||||
<h1>My Drafts</h1>
|
||||
<div>You need to be authenticated to view this page.</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="page">
|
||||
<h1>My Drafts</h1>
|
||||
<main>
|
||||
{props.drafts.map((post) => (
|
||||
<div key={post.id} className="post">
|
||||
<Post post={post} />
|
||||
</div>
|
||||
))}
|
||||
</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 Drafts;
|
||||
@ -1,91 +0,0 @@
|
||||
import React from "react";
|
||||
import { GetServerSideProps } from "next";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import Layout from "../../../components/Layout";
|
||||
import Router from "next/router";
|
||||
import { PostProps } from "../../../components/Post";
|
||||
import prisma from '../../../lib/prisma'
|
||||
import { useSession } from "next-auth/react";
|
||||
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
|
||||
const post = await prisma.post.findUnique({
|
||||
where: {
|
||||
id: Number(params?.id) || -1,
|
||||
},
|
||||
include: {
|
||||
author: {
|
||||
select: { name: true, email: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
props: post,
|
||||
};
|
||||
};
|
||||
|
||||
async function publishPost(id: number): Promise<void> {
|
||||
await fetch(`/api/publish/${id}`, {
|
||||
method: "PUT",
|
||||
});
|
||||
await Router.push("/")
|
||||
}
|
||||
|
||||
async function deletePost(id: number): Promise<void> {
|
||||
await fetch(`/api/post/${id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
await Router.push("/")
|
||||
}
|
||||
|
||||
const Post = (props: PostProps) => {
|
||||
const { data: session, status } = useSession();
|
||||
if (status === 'loading') {
|
||||
return <div>Authenticating ...</div>;
|
||||
}
|
||||
const userHasValidSession = Boolean(session);
|
||||
const postBelongsToUser = session?.user?.email === props.author?.email;
|
||||
let title = props.title;
|
||||
if (!props.published) {
|
||||
title = `${title} (Draft)`;
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
<p>By {props?.author?.name || "Unknown author"}</p>
|
||||
<ReactMarkdown children={props.content} />
|
||||
{!props.published && userHasValidSession && postBelongsToUser && (
|
||||
<button onClick={() => publishPost(props.id)}>Publish</button>
|
||||
)}
|
||||
{userHasValidSession && postBelongsToUser && (
|
||||
<button onClick={() => deletePost(props.id)}>Delete</button>
|
||||
)}
|
||||
</div>
|
||||
<style jsx>{`
|
||||
.page {
|
||||
background: white;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.actions {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
button {
|
||||
background: #ececec;
|
||||
border: 0;
|
||||
border-radius: 0.125rem;
|
||||
padding: 1rem 2rem;
|
||||
}
|
||||
|
||||
button + button {
|
||||
margin-left: 1rem;
|
||||
}
|
||||
`}</style>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default Post;
|
||||
@ -1,171 +0,0 @@
|
||||
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 Router from "next/router";
|
||||
import { ProfileProps } from "../../types/profile";
|
||||
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 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);
|
||||
|
||||
|
||||
// il n'existe pas ? on le crée
|
||||
if (isUserProfile.length <= 0) {
|
||||
const newProfil = await prisma.profile.create({
|
||||
data: {
|
||||
bio: "",
|
||||
user: {
|
||||
connect: { email: session.user.email },
|
||||
},
|
||||
},
|
||||
});
|
||||
console.log('newProfil', newProfil);
|
||||
|
||||
}
|
||||
|
||||
// on renvoi le profil
|
||||
return { props: { isUserProfile } };
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
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<UserSubmitForm>({
|
||||
resolver: yupResolver(validationSchema)
|
||||
});
|
||||
|
||||
const [response, setResponse] = useState<ResponseData | undefined>();
|
||||
const { data: session } = useSession();
|
||||
|
||||
React.useEffect(() => {
|
||||
console.log('user profil props', isUserProfile)
|
||||
}, [])
|
||||
|
||||
const onSubmit = async (data: UserSubmitForm) => {
|
||||
console.log(data);
|
||||
|
||||
try {
|
||||
const body = { bioValue: data.bio };
|
||||
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>
|
||||
|
||||
<div className="register-form">
|
||||
<p>Ma bio : {isUserProfile[0]?.bio}</p>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="form-group">
|
||||
<label>Ma bio :</label>
|
||||
<input
|
||||
placeholder="Ma bio..."
|
||||
defaultValue={isUserProfile[0]?.bio}
|
||||
type="text"
|
||||
{...register('bio')}
|
||||
className={`form-control ${errors.bio ? 'is-invalid' : ''}`}
|
||||
/>
|
||||
<div className="invalid-feedback">{errors.bio?.message}</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="form-group">
|
||||
<button type="submit" className="btn btn-primary">
|
||||
Valider les changements
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => reset()}
|
||||
className="btn btn-warning float-right"
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
|
||||
<p>Email : {session.user.email}</p>
|
||||
{response && <p>{response.message}</p>}
|
||||
</main>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
|
||||
export default Profil;
|
||||
Loading…
Reference in new issue