Buncha changes I CBA
This commit is contained in:
parent
2764039835
commit
89f3f86c54
@ -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);
|
||||
|
||||
103
src/app/api/post/route.ts
Normal file
103
src/app/api/post/route.ts
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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> = T extends object ? {
|
||||
[P in keyof T]?: DeepPartial<T[P]>;
|
||||
} : T;
|
||||
|
||||
export default async function Test() {
|
||||
|
||||
const response = await fetch(constructAPIUrl('post'));
|
||||
|
||||
const response = await fetch("http://localhost:3000/api2/post/");
|
||||
const articles:Array<DeepPartial<Post>> = await response.json();
|
||||
|
||||
const articles:Array<DeepPartial<PostAttributes>> = await response.json();
|
||||
|
||||
return <div className={`root`}>
|
||||
<Header/>
|
||||
|
||||
@ -3,7 +3,7 @@ import styles from "./header.module.css"
|
||||
export default function Header() {
|
||||
return <div className={`${styles.header} pp`}>
|
||||
|
||||
<img src="/logo.png" width="64px" height="auto" alt="" />
|
||||
<img src="/logo.png" width="80px" height="auto" alt="" />
|
||||
<div className={styles.headertitle}>
|
||||
<div style={{flexGrow:1}}>Andreas<br/>Schaafsma</div>
|
||||
<div>>Software Developer</div>
|
||||
|
||||
19
src/db.ts
19
src/db.ts
@ -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<Connection>{
|
||||
const connection = mysql2.createConnection(connectionInfo);
|
||||
return connection;
|
||||
}
|
||||
export const connection = getConnection();
|
||||
|
||||
// export default getConnection;
|
||||
@ -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<User['id']>;
|
||||
}
|
||||
export type PostCreationAttributes = {
|
||||
title: string;
|
||||
content: string;
|
||||
date: number;
|
||||
user_id:number;
|
||||
}
|
||||
|
||||
export class Post extends Model<InferAttributes<Post>, InferCreationAttributes<Post>> {
|
||||
declare id: number|null;
|
||||
declare title: string;
|
||||
declare content: string;
|
||||
declare date: number;
|
||||
export class Post extends Model<PostAttributes, PostCreationAttributes> {
|
||||
declare id: number;
|
||||
declare user:NonAttribute<User>;
|
||||
declare user_id:ForeignKey<User['id']>;
|
||||
declare getUser: BelongsToGetAssociationMixin<User>;
|
||||
@ -73,6 +83,7 @@ Post.init(
|
||||
date: {
|
||||
type: DataTypes.DATE
|
||||
},
|
||||
|
||||
},
|
||||
{
|
||||
tableName: 'Posts',
|
||||
|
||||
19
src/util/Utils.ts
Normal file
19
src/util/Utils.ts
Normal file
@ -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 }
|
||||
Loading…
x
Reference in New Issue
Block a user