diff --git a/src/app/api2/[...slug]/route.ts b/src/app/api/[...slug]/route.ts similarity index 92% rename from src/app/api2/[...slug]/route.ts rename to src/app/api/[...slug]/route.ts index 4013ff7..0eed7a0 100644 --- a/src/app/api2/[...slug]/route.ts +++ b/src/app/api/[...slug]/route.ts @@ -1,13 +1,12 @@ 'use server' -import { MPost } from "@/model/Models"; import { cookies } from "next/headers"; export async function GET(request:Request, { params }: {params:{slug: string}}){ console.log(request); - const url:NextURL = request.url; - console.log(url); + // const url:NextURL = request.url; + // console.log(url); console.log(request); console.log(params); diff --git a/src/app/api2/auth/route.ts b/src/app/api/auth/route.ts similarity index 100% rename from src/app/api2/auth/route.ts rename to src/app/api/auth/route.ts diff --git a/src/app/api2/post/[...slug]/route.ts b/src/app/api/post/[...slug]/route.ts similarity index 100% rename from src/app/api2/post/[...slug]/route.ts rename to src/app/api/post/[...slug]/route.ts diff --git a/src/app/api/post/route.ts b/src/app/api/post/route.ts new file mode 100644 index 0000000..ac27579 --- /dev/null +++ b/src/app/api/post/route.ts @@ -0,0 +1,103 @@ +'use server' + +import { APIError } from "@/api/error"; +import { Auth, Post, User } from "@/model/sequelize/NewModels"; +import { cookies } from "next/headers"; +import { where } from "sequelize"; + + + +async function tryCreatePost(request: Request) { + + // Make sure the DB is ready + await Post.sync(); + + // Prepare data + const requestBody = await request.json(); + const authCkie = await cookies().get("auth"); + + // Sanity check auth cookie + if ( !authCkie || !authCkie.value) throw new APIError({ status: 500, responseText: "missing auth cookie" }); + + // Get JSON from the Cookie + const cookieJSON = authCkie.value; + const authObject = JSON.parse(cookieJSON); + + // Fetch User Auth from the database + const auth = await Auth.findOne({ include: 'user', where: { token: authObject.token } }); + + // Sanity check the auth and associated user + if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" }); + const user = auth.user; + + // Handle incomplete data or other problems + if (!requestBody) throw new APIError({ status: 500, responseText: "Empty request body" }); + if (!requestBody.title) throw new APIError({ status: 500, responseText: "Missing post title" }); + if (!requestBody.content) throw new APIError({ status: 500, responseText: "Missing post content" }); + if (!user.id) throw new APIError({ status: 500, responseText: "Missing user id" }); + + // Create a new Post in the database + const post = await Post.create( + { + content: requestBody.content, + user_id: user.id, + title: requestBody.title, + date: Date.now() + },{include: "user"}) + // // Find the post (Unneeded but nice to check) + // const foundPost = await Post.findOne({ + // include: "user", + // where: { + // id: post.id + // } + // }) + + return new Response(JSON.stringify(Post), { status: 200 }); + +} + +export async function POST(request: Request) { + try { + return await tryCreatePost(request); + } + catch (e) { + if (e instanceof APIError) { + return new Response(e.info.responseText, { status: e.info.status }); + } + else { + throw e; + } + } +} + + +async function tryFetchPosts(request: Request) { + + await Post.sync(); + + const foundPosts = await Post.findAll({ + include: [{ + association: 'user', + attributes: { exclude: ['password', 'createdAt', 'updatedAt'] } + }] + }); + + return new Response(JSON.stringify(foundPosts), { status: 200 }); + +} + + +export async function GET(request: Request) { + try { + return await tryFetchPosts(request); + } + catch (e) { + if (e instanceof APIError) { + return new Response(e.info.responseText, { status: e.info.status }); + } + else { + throw e; + } + } +} + diff --git a/src/app/api2/user/route.ts b/src/app/api/user/route.ts similarity index 100% rename from src/app/api2/user/route.ts rename to src/app/api/user/route.ts diff --git a/src/app/api2/post/route.ts b/src/app/api2/post/route.ts deleted file mode 100644 index 7e42b79..0000000 --- a/src/app/api2/post/route.ts +++ /dev/null @@ -1,104 +0,0 @@ -'use server' - -import { APIError } from "@/api/error"; -import { Auth, Post, User } from "@/model/sequelize/NewModels"; -import { cookies } from "next/headers"; -import { where } from "sequelize"; - - - -async function tryCreatePost(request:Request){ - await Post.sync(); - - - const requestBody = await request.json(); - - const authCookie = await cookies().get("auth"); - - if(!authCookie || !authCookie.value) throw new APIError({status:500,responseText: "missing auth cookie"}); - - const cookieJSON = authCookie.value; - - const authObject = JSON.parse(cookieJSON); - - const auth = await Auth.findOne({include: 'user', where:{token: authObject.token}}); - - - if(!auth || !auth.user) throw new APIError({status:401,responseText: "Authentication Error"}); - - const user = auth.user; - - - - // return new Response(JSON.stringify({auth,user}),{status:200}); - - - if (!requestBody) throw new APIError({status:500,responseText: "Empty request body"}); - if (!requestBody.title) throw new APIError({status:500,responseText: "Missing post title"}); - if (!requestBody.content) throw new APIError({status:500,responseText: "Missing post content"}); - // if (!requestBody.user_id) throw new APIError({status:500,responseText: "Missing user id"}); - - const post = await Post.create({ - content:requestBody.content, - user_id:user.id, - title:requestBody.title, - date:Date.now() - }) - - const foundPost = await Post.findOne({ - include:"user", - where:{ - id:post.id - } - }) - - - return new Response(JSON.stringify(foundPost),{status:200}); - -} - -export async function POST(request:Request){ - try{ - return await tryCreatePost(request); - } - catch(e){ - if (e instanceof APIError){ - return new Response(e.info.responseText,{status:e.info.status}); - } - else{ - throw e; - } - } -} - - -async function tryFetchPosts(request:Request){ - - await Post.sync(); - - const foundPosts = await Post.findAll({ - include: [{ - association: 'user', - attributes:{exclude:['password','createdAt','updatedAt']} - }] - }); - - return new Response(JSON.stringify(foundPosts),{status:200}); - -} - - -export async function GET(request:Request){ - try{ - return await tryFetchPosts(request); - } - catch(e){ - if (e instanceof APIError){ - return new Response(e.info.responseText,{status:e.info.status}); - } - else{ - throw e; - } - } -} - diff --git a/src/app/page.tsx b/src/app/page.tsx index c121e7b..ad48756 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -6,17 +6,18 @@ import ArticlePreview from "@/components/news/article-preview" import ReactDOM from "react"; import "public/global.css" import "./index.css" -import { Post } from "@/model/sequelize/NewModels"; +import { Post, PostAttributes } from "@/model/sequelize/NewModels"; +import { constructAPIUrl } from "@/util/Utils"; type DeepPartial = T extends object ? { [P in keyof T]?: DeepPartial; } : T; export default async function Test() { + + const response = await fetch(constructAPIUrl('post')); - const response = await fetch("http://localhost:3000/api2/post/"); - const articles:Array> = await response.json(); - + const articles:Array> = await response.json(); return
diff --git a/src/components/header.tsx b/src/components/header.tsx index 8c93b47..f9ed826 100644 --- a/src/components/header.tsx +++ b/src/components/header.tsx @@ -3,7 +3,7 @@ import styles from "./header.module.css" export default function Header() { return
- +
Andreas
Schaafsma
>Software Developer
diff --git a/src/db.ts b/src/db.ts deleted file mode 100644 index 0488d35..0000000 --- a/src/db.ts +++ /dev/null @@ -1,19 +0,0 @@ -import mysql from "mysql2"; -import mysql2, { Connection } from "mysql2"; - -const connectionInfo:mysql.ConnectionOptions = { - host: '127.0.0.1', - port: 3306, - user: 'user', - password: 'password', - database: 'portfolio', - -}; - -export async function getConnection():Promise{ - const connection = mysql2.createConnection(connectionInfo); - return connection; -} -export const connection = getConnection(); - -// export default getConnection; \ No newline at end of file diff --git a/src/model/sequelize/NewModels.ts b/src/model/sequelize/NewModels.ts index cd1e6a2..e96d902 100644 --- a/src/model/sequelize/NewModels.ts +++ b/src/model/sequelize/NewModels.ts @@ -42,12 +42,22 @@ Auth.init({ sequelize // passing the `sequelize` instance is required }); +export type PostAttributes = { + id: number; + title: string; + content: string; + date: number; + user_id:ForeignKey; +} +export type PostCreationAttributes = { + title: string; + content: string; + date: number; + user_id:number; +} -export class Post extends Model, InferCreationAttributes> { - declare id: number|null; - declare title: string; - declare content: string; - declare date: number; +export class Post extends Model { + declare id: number; declare user:NonAttribute; declare user_id:ForeignKey; declare getUser: BelongsToGetAssociationMixin; @@ -73,6 +83,7 @@ Post.init( date: { type: DataTypes.DATE }, + }, { tableName: 'Posts', diff --git a/src/util/Utils.ts b/src/util/Utils.ts new file mode 100644 index 0000000..006dd99 --- /dev/null +++ b/src/util/Utils.ts @@ -0,0 +1,19 @@ +import Gens from "./gens"; +import Auth from "./Auth"; + + +function getAPIEnv(){ + return { + 'schema': process.env.API_SCHEMA, + 'host': process.env.API_HOST, + 'port': process.env.API_PORT, + 'basepath': process.env.API_BASEPATH + }; +} +function constructAPIUrl(endpoint:string){ + const { schema, host, port, basepath } = getAPIEnv(); + return `${schema}://${host}:${port}/${basepath}/${endpoint}` +} + + +export { Gens, Auth, constructAPIUrl } \ No newline at end of file diff --git a/src/gens.ts b/src/util/gens.ts similarity index 100% rename from src/gens.ts rename to src/util/gens.ts