Skip to content
Snippets Groups Projects
Commit b6abb261 authored by DESKTOP-9FO96TP\hehexd's avatar DESKTOP-9FO96TP\hehexd
Browse files

created MessageListPage, created Api Route for Messages with Post request, dataBase created

parent 9898c7ba
No related branches found
No related tags found
1 merge request!3Implement message schema
Pipeline #32981 passed
import {PrismaClient} from "@prisma/client"
import { NextApiRequest, NextApiResponse } from "next"
import { NextRequest, NextResponse } from "next/server"
import { prisma } from './../../../prisma/db'
export async function GET(req: NextRequest){
return NextResponse.json("")
}
export async function POST(req: NextRequest, res: NextResponse){
const data = await req.json()
console.log("router data: " + data, "status:")
console.log(data)
try {
await prisma.message.create({
data: data
})
return NextResponse.json({status: 201, message: 'Message Created'})
//res.status(200).json({message: 'Message Created'})
//res.status(200).json({message: 'Message Created'})
} catch (error) {
console.log("Failure" + error);
// res.status(400)
}
console.log("post")
}
/*
export default async function handler(req: NextApiRequest, res: NextApiResponse){
const data = (req.body)
try {
await prisma.message.create({
data
})
res.status(200).json({message: 'Note Created'})
} catch (error) {
console.log("Failure");
}
} */
/* export const postMessage = async(req: NextApiRequest , res: NextApiResponse) => {
const data = (req.body)
console.log("router data: " + data)
const createdMessage = await prisma.message.create({
data
})
res.status(201)
} */
\ No newline at end of file
"use client"
import { useState } from "react"
import { PrismaClient, Message } from "@prisma/client"
export default function PostMessageForm(props: {data: Message[]}){
const [formData, setFormData] = useState({})
const [messagesState, setMessages] = useState(props.data)
async function postMessage(e:any) {
e.preventDefault()
/* setMessages([...messagesState, formData]) */
console.log(formData)
const response = await fetch('http://localhost:3000/api/messages', {
method: 'POST',
body: JSON.stringify(formData)
})
return await response.json()
}
return (<div>
<form onSubmit={postMessage}>
<input type="text" placeholder="content" name="content" onChange={e => setFormData({ ...formData, content : e.target.value })}/>
<textarea name="content" id="" cols={30} rows={10} placeholder="content" onChange={e => setFormData({ ...formData, content: e.target.value })} />
<button type="submit">Post Message</button>
</form>
</div>)
}
\ No newline at end of file
import { PrismaClient } from "@prisma/client" import { Message } from "@prisma/client"
import React from "react"
import PostMessageForm from "./PostMessageForm";
import { prisma } from "@/prisma/db";
const prisma = new PrismaClient() // Define a type for our props
interface MessageProps {
data: Message[];
}
export default async function MessageList() { export default async function MessageList({data}:MessageProps) {
const messages = await prisma.message.findMany() const messages = await prisma.message.findMany()
...@@ -10,8 +16,27 @@ export default async function MessageList() { ...@@ -10,8 +16,27 @@ export default async function MessageList() {
<div> <div>
Message List Page Message List Page
{messages.map((msg) => ( {messages.map((msg) => (
<li key = "msg.id"> author: {msg.author} message: {msg.content} </li> <li key = {msg.id}> author: {msg.author} message: {msg.content} sentAt: {msg.sentAt?.toString()} </li>
))} ))}
<PostMessageForm data={messages}></PostMessageForm>
</div> </div>
) )
}
export async function getServerSideProps() {
const formData = {description: 'sdfsdf', content: 'sdfsdf'}
const response = await fetch('/api/messages', {
method: 'POST',
body: JSON.stringify(formData)
})
console.log("answer:" + await response.json())
const messages = await prisma.message.findMany()
return {
props: {
data: messages
}
}
} }
\ No newline at end of file
import { PrismaClient } from '@prisma/client'
const globalForPrisma = global as unknown as {
prisma: PrismaClient | undefined
}
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: ['query'],
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
\ No newline at end of file
No preview for this file type
-- RedefineTables
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Message" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"author" TEXT,
"gameId" TEXT,
"title" TEXT,
"content" TEXT NOT NULL,
"sentAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME
);
INSERT INTO "new_Message" ("author", "content", "gameId", "id", "sentAt", "title", "updatedAt") SELECT "author", "content", "gameId", "id", "sentAt", "title", "updatedAt" FROM "Message";
DROP TABLE "Message";
ALTER TABLE "new_Message" RENAME TO "Message";
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;
-- RedefineTables
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Message" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"author" TEXT,
"gameId" TEXT,
"title" TEXT,
"content" TEXT NOT NULL,
"sentAt" DATETIME DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME
);
INSERT INTO "new_Message" ("author", "content", "gameId", "id", "sentAt", "title", "updatedAt") SELECT "author", "content", "gameId", "id", "sentAt", "title", "updatedAt" FROM "Message";
DROP TABLE "Message";
ALTER TABLE "new_Message" RENAME TO "Message";
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;
...@@ -12,10 +12,10 @@ datasource db { ...@@ -12,10 +12,10 @@ datasource db {
model Message{ model Message{
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
author String author String?
gameId String gameId String?
title String title String?
content String content String
sentAt DateTime @default(now()) sentAt DateTime? @default(now())
updatedAt DateTime? @updatedAt updatedAt DateTime? @updatedAt
} }
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment