From 66d20e156d735cf886b4b8096acee3ff32a8550b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luc=C3=A0s?= Date: Tue, 11 Apr 2023 22:02:33 +0200 Subject: [PATCH] fix: add types and cleanup code --- src/components/form/RegisterForm.tsx | 279 +++++++++++++-------------- src/pages/api/auth/[...nextauth].ts | 24 +-- src/pages/api/socket/chat/[id].ts | 19 +- src/pages/chat/[id].tsx | 28 +-- 4 files changed, 163 insertions(+), 187 deletions(-) diff --git a/src/components/form/RegisterForm.tsx b/src/components/form/RegisterForm.tsx index d3d3234..2b7635d 100644 --- a/src/components/form/RegisterForm.tsx +++ b/src/components/form/RegisterForm.tsx @@ -8,12 +8,12 @@ import { Input, Container, FormErrorMessage, -} from "@chakra-ui/react"; -import { useRouter } from "next/router"; -import { useState } from "react"; -import { signIn, SignInResponse } from "next-auth/react"; -import { RegisterData } from "@/models/form/RegisterData"; -import { useForm } from "react-hook-form"; +} from '@chakra-ui/react'; +import {useRouter} from 'next/router'; +import {useState} from 'react'; +import {signIn, SignInResponse} from 'next-auth/react'; +import {RegisterData} from '@/models/form/RegisterData'; +import {SubmitHandler, useForm} from 'react-hook-form'; export default function RegisterForm() { const router = useRouter(); @@ -22,25 +22,23 @@ export default function RegisterForm() { handleSubmit, register, watch, - formState: { errors, isSubmitting }, + formState: {errors, isSubmitting}, } = useForm(); - const buttonWidth = { base: "100%", md: "unset" }; - const validateDate = (value: string) => { const selected = new Date(value).getFullYear(); const now = new Date().getFullYear(); - return now - selected >= 18 || "Vous devez avoir 18 ans ou plus"; + return now - selected >= 18 || 'Vous devez avoir 18 ans ou plus'; }; - const registerUser = (values: RegisterData) => { - let { email, firstName, lastName, birthdate, password, confirmPassword } = - values; + const submitHandler: SubmitHandler = (values: RegisterData) => { + let {email, firstName, lastName, birthdate, password, confirmPassword} = + values; const date = new Date(birthdate); const options = { - method: "POST", - headers: { "Content-Type": "application/json" }, + method: 'POST', + headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email, firstName, @@ -50,143 +48,142 @@ export default function RegisterForm() { }), }; - fetch("/api/users", options) - .then(() => { - signIn("credentials", { email, password, redirect: false }).then( + fetch('/api/users', options).then(() => { + signIn('credentials', {email, password, redirect: false}).then( (res: unknown) => { - const { ok: connexionSuccess } = res as SignInResponse; + const {ok: connexionSuccess} = res as SignInResponse; // TODO If success -> goto interactive form else login - router.push(connexionSuccess ? "/dashboard" : "/"); - } - ); - }) - .catch(() => {}); + router.push(connexionSuccess ? '/dashboard' : '/'); + }, + ); + }).catch((err) => console.error(err)); }; return ( - - -
- - Inscription - + + + + + Inscription + - - {/*Prénom*/} - - Prénom + + {/*Prénom*/} + + Prénom + + {errors.firstName?.message as string} + + + {/*Nom*/} + + Nom + + {errors.lastName?.message as string} + + + + {/*Email*/} + + Adresse email - {errors.firstName?.message} + {errors.email?.message as string} - {/*Nom*/} - - Nom - - {errors.lastName?.message} - - - - {/*Email*/} - - Adresse email - - {errors.email?.message} - - - {/*Date de naissance*/} - - Date de naissance - - {errors.birthdate?.message} - - - {/*Mot de passe*/} - - Mot de passe - - {errors.password?.message} - - - {/*Mot de passe (2)*/} - - Confirmation du mot de passe - { - return ( - watch("password") === value || - "Les mots de passe ne correspondent pas" - ); - }, - })} - /> - - {errors.confirmPassword?.message} - - - - - - - - - -
+ Date de naissance + + { (errors.birthdate) ? {errors.birthdate.message as string} : "" } + + + {/*Mot de passe*/} + + Mot de passe + + {errors.password?.message as string} + + + {/*Mot de passe (2)*/} + + Confirmation du mot de passe + { + return ( + watch('password') === value || + 'Les mots de passe ne correspondent pas' + ); + }, + })} + /> + {errors.confirmPassword?.message as string} + + + + + + + +
+
); } diff --git a/src/pages/api/auth/[...nextauth].ts b/src/pages/api/auth/[...nextauth].ts index 104fa83..fd7aaa6 100644 --- a/src/pages/api/auth/[...nextauth].ts +++ b/src/pages/api/auth/[...nextauth].ts @@ -1,9 +1,11 @@ import NextAuth from 'next-auth'; import CredentialsProvider from 'next-auth/providers/credentials'; import {NextApiRequest, NextApiResponse} from 'next'; + import {LoginData} from '@/models/form/LoginData'; import {isSamePassword} from '@/lib/PasswordTools'; -import {User} from '@prisma/client'; + +import type {User} from '@prisma/client'; import prismaClient from '@/lib/prismaClient'; export default async function auth(req: NextApiRequest, res: NextApiResponse) { @@ -11,27 +13,19 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) { CredentialsProvider({ name: 'Credentials', credentials: { - email: { - label: 'Email', - type: 'text', - placeholder: 'adresse@email.com' - }, - password: { - label: 'Password', - type: 'password', - placeholder: 'mot de passe', - }, + email: {label: 'Email', type: 'text'}, + password: {label: 'Password', type: 'password'}, }, async authorize(credentials: unknown) { const {email, password} = credentials as LoginData; if (!email || !password) return null; // Appel à la base de donnée - const user = await getUserByEmail(email); + const user: User | null = await getUserByEmail(email); if (!user) return null; // Vérification de la connexion - const passwordIsValid = await isSamePassword(password, user.password); + const passwordIsValid: boolean = await isSamePassword(password, user.password); if (passwordIsValid) return user; else return null; }, @@ -46,7 +40,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) { signOut: '/auth/signout', error: '/auth/error', verifyRequest: '/auth/verify-request', - newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest) + newUser: '/auth/new-user', // New users will be directed here on first sign in (leave the property out if not of interest) }, secret: process.env.NEXTAUTH_SECRET, callbacks: { @@ -62,6 +56,6 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) { async function getUserByEmail(email: string): Promise { return prismaClient.user.findUnique({ - where: {email} + where: {email}, }); } \ No newline at end of file diff --git a/src/pages/api/socket/chat/[id].ts b/src/pages/api/socket/chat/[id].ts index 4eb0ce5..ee4d925 100644 --- a/src/pages/api/socket/chat/[id].ts +++ b/src/pages/api/socket/chat/[id].ts @@ -1,10 +1,10 @@ import {Server} from 'socket.io'; import prismaClient from '@/lib/prismaClient'; +import type {Chat, Message as Message} from '@prisma/client'; export default async function SocketHandler(req: any, res: any) { const {id: chatId} = req.query; - // It means that socket server was already initialised if (res.socket.server.io) { console.log('Already set up'); res.end(); @@ -14,17 +14,13 @@ export default async function SocketHandler(req: any, res: any) { const io = new Server(res.socket.server); res.socket.server.io = io; - // Define actions inside - io.on('connection', async (socket) => { - console.log(socket.id); + io.on('connection', async (socket): Promise => { await prismaClient.chat.findFirst({ - where: {id: chatId}, - include: {Message: true}, - }).then(chat => { - // @ts-ignore - return socket.emit('allOldMessages', chat.Message); - }); + where: {id: chatId}, include: {Message: true}, + }).then((chat: (Chat & { Message: Message[] }) | null) => + {if (chat) socket.emit('allOldMessages', chat.Message)} + ); socket.on('createdMessage', async (msgInput) => { await prismaClient.message.create({ @@ -33,10 +29,9 @@ export default async function SocketHandler(req: any, res: any) { User: {connect: {id: msgInput.sender}}, Chat: {connect: {id: chatId}}, }, - }).then((newMessage) => socket.emit('newIncomingMessage', newMessage)); + }).then((newMessage: Message) => socket.emit('newIncomingMessage', newMessage)); }); }); - console.log('Setting up socket'); res.end(); } \ No newline at end of file diff --git a/src/pages/chat/[id].tsx b/src/pages/chat/[id].tsx index 7e6f24b..527a684 100644 --- a/src/pages/chat/[id].tsx +++ b/src/pages/chat/[id].tsx @@ -3,12 +3,12 @@ import Head from 'next/head'; import {websiteName} from '@/lib/constants'; import {useSession} from 'next-auth/react'; import {useRouter} from 'next/router'; -import {useCallback, useEffect, useState} from 'react'; +import {useEffect, useState} from 'react'; import MessageList from '@/components/chat/MessageList'; import {io, Socket} from 'socket.io-client'; -import {Message} from '@prisma/client'; +import {Message, User} from '@prisma/client'; export default function ChatId() { const router = useRouter(); @@ -26,22 +26,13 @@ export default function ChatId() { const socketInitializer = async () => { await fetch(`/api/socket/chat/${chatId}`) - const soc = io() + const soc = io(); - soc.on('connect', () => { - console.log('connected') - }) - - soc.on("allOldMessages", (allOldMessages: Message[]) => { - console.log("allOldMessages", allOldMessages); - setMessages(allOldMessages); - }) - - soc.on("newIncomingMessage", (newIncomingMessage: Message) => { - console.log("newIncomingMessage", newIncomingMessage); - console.log("messages", messages); - setMessages(messages => ([...messages, newIncomingMessage])); - }); + soc.on('connect', () => console.log('connected')) + soc.on("allOldMessages", (allOldMessages: Message[]) => setMessages(allOldMessages)) + soc.on("newIncomingMessage", (newIncomingMessage: Message) => + setMessages(messages => [...messages, newIncomingMessage]) + ); setSocket(soc); } @@ -50,7 +41,6 @@ export default function ChatId() { const handleSubmit = () => { if (text !== "" && socket) { - // @ts-ignore socket.emit("createdMessage", {text, sender: session.user.id}) setText(""); } @@ -62,7 +52,7 @@ export default function ChatId() { {websiteName} - + setText(evt.target.value) } value={text} />