Skip to content

Commit 57aee09

Browse files
authored
Merge pull request #1 from jesieldotdev/new-db
New db
2 parents 4327c75 + 7585f53 commit 57aee09

File tree

9 files changed

+501
-72
lines changed

9 files changed

+501
-72
lines changed

.env

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
SUPABASE_URL=https://smjvdyhhwzdzvloweoxt.supabase.co
2+
SUPABASE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNtanZkeWhod3pkenZsb3dlb3h0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzA5ODkzMDQsImV4cCI6MjA0NjU2NTMwNH0.-3NznwUsudhDwP03sXVOYufG-_ARGHDpXF99R9Ah8oc

package.json

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,22 @@
99
"lint": "next lint"
1010
},
1111
"dependencies": {
12+
"@supabase/supabase-js": "^2.46.1",
13+
"bufferutil": "^4.0.8",
14+
"next": "latest",
15+
"pg": "^8.13.1",
16+
"pg-hstore": "^2.3.4",
1217
"react": "latest",
1318
"react-dom": "latest",
14-
"next": "latest"
19+
"sequelize": "^6.37.5",
20+
"utf-8-validate": "^6.0.5"
1521
},
1622
"devDependencies": {
17-
"typescript": "latest",
18-
"@types/react": "latest",
1923
"@types/node": "latest",
24+
"@types/react": "latest",
2025
"@types/react-dom": "latest",
2126
"eslint": "latest",
22-
"eslint-config-next": "latest"
27+
"eslint-config-next": "latest",
28+
"typescript": "latest"
2329
}
2430
}

src/app/api/blog/route.ts

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,35 @@
11
import { getPosts, addPost, deletePost } from "@/app/lib/data"
22
import { NextResponse } from "next/server"
33

4-
5-
export const GET = async (req: Request, res: Response) => {
6-
7-
try{
8-
const posts = getPosts()
4+
export const GET = async (req: Request) => {
5+
try {
6+
// Aguarda a resolução da promessa
7+
const posts = await getPosts();
98

10-
return NextResponse.json({message: 'OK', posts},{
11-
status: 200
12-
})
9+
return NextResponse.json({ message: 'OK', posts }, { status: 200 });
1310
} catch (err) {
14-
return NextResponse.json({message: 'Error', err}, {
15-
status: 500,
16-
})
11+
if (err instanceof Error) {
12+
return NextResponse.json({ message: 'Error', err: err.message }, { status: 500 });
13+
} else {
14+
return NextResponse.json({ message: 'Unknown error' }, { status: 500 });
15+
}
1716
}
17+
1818
}
1919

20-
export const POST = async (req: Request, res: Response) => {
21-
const {title, desc} = await req.json()
20+
export const POST = async (req: Request) => {
21+
const { title } = await req.json();
2222

2323
try {
24-
const post = {title, desc, date: new Date(), id: Date.now().toString()}
25-
addPost(post)
26-
return NextResponse.json({message: "Ok", post}, {status: 201})
27-
} catch (err){
28-
return NextResponse.json({message: 'Error', err}, {
29-
status: 500
30-
})
24+
const post = { title };
25+
await addPost(post); // Garantir que a função addPost aguarde a inserção do post
26+
return NextResponse.json({ message: "Ok", post }, { status: 201 });
27+
} catch (err) {
28+
if (err instanceof Error) {
29+
return NextResponse.json({ message: 'Error', err: err.message }, { status: 500 });
30+
} else {
31+
return NextResponse.json({ message: 'Unknown error' }, { status: 500 });
32+
}
3133
}
34+
3235
}
33-
34-
35-
36-

src/app/lib/data.ts

Lines changed: 53 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,66 @@
1-
import file from "../api/posts.json" assert { type: "json" };
2-
const fs = require("fs");
3-
const customer =
4-
{
5-
name: "d Co.",
6-
order_count: 0,
7-
address: "Po Box City",
8-
}
9-
10-
function saveJson(data:any){
11-
const jsonString = JSON.stringify(data);
12-
fs.writeFile("./src/app/api/posts.json", jsonString, (err:any) => {
13-
if (err) {
14-
console.log("Error writing file", err);
15-
} else {
16-
console.log("Successfully wrote file");
17-
}
18-
});
19-
}
1+
import supabase from '../../config/database'; // Importando o cliente Supabase
202

3+
// Obter todos os posts
4+
export const getPosts = async () => {
5+
const { data, error } = await supabase
6+
.from('posts') // Nome da tabela
7+
.select('*'); // Seleciona todos os campos
218

9+
console.log(data)
2210

23-
type Post = {
24-
id: string;
25-
title: string;
26-
desc: string;
27-
date: any;
11+
if (error) throw new Error(error.message);
12+
return data;
2813
};
2914

30-
let posts: Post[] = file;
15+
// Adicionar um novo post
16+
export const addPost = async (post: { title: string; }) => {
17+
const { data, error } = await supabase
18+
.from('posts') // Nome da tabela
19+
.insert([
20+
{title: post.title }
21+
]);
3122

32-
export const getPosts = () => posts;
33-
export const addPost = (post: Post) => {
34-
posts.push(post);
35-
saveJson(posts)
23+
if (error) throw new Error(error.message);
24+
return data;
3625
};
37-
export const deletePost = (id: string) => {
38-
posts = posts.filter((post) => post.id !== id);
39-
saveJson(posts)
40-
};
41-
export const updatePost = (id: string, title: string, desc: string) => {
42-
const post = posts.find((post) => post.id === id);
43-
4426

45-
if (post) {
46-
post.title = title;
47-
post.desc = desc;
48-
saveJson(posts)
49-
} else {
27+
// Deletar um post pelo id
28+
export const deletePost = async (id: string) => {
29+
const { data, error } = await supabase
30+
.from('posts')
31+
.delete()
32+
.eq('id', id); // A condição de deletar pelo id
33+
34+
if (error) throw new Error(error.message);
35+
if (!data) {
5036
throw new Error("NO POST FOUND");
5137
}
38+
39+
40+
return data;
41+
};
42+
43+
// Atualizar um post pelo id
44+
export const updatePost = async (id: string, title: string, desc: string) => {
45+
const { data, error } = await supabase
46+
.from('posts')
47+
.update({ title, desc })
48+
.eq('id', id); // A condição de atualizar pelo id
49+
50+
if (error) throw new Error(error.message);
51+
if (!data) throw new Error("NO POST FOUND");
52+
return data;
5253
};
5354

54-
export const getById = (id: string) => {
55-
return posts.find((post) => post.id === id);
55+
// Obter um post pelo id
56+
export const getById = async (id: string) => {
57+
const { data, error } = await supabase
58+
.from('posts')
59+
.select('*')
60+
.eq('id', id)
61+
.single(); // Para pegar apenas um resultado (usamos .single() para retornar um único item)
62+
63+
if (error) throw new Error(error.message);
64+
if (!data) throw new Error("NO POST FOUND");
65+
return data;
5666
};

src/app/page.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export default function Home() {
44
return (
55
<main>
66
<p>My Api</p>
7+
<a href='/api/blog'>Blog</a>
78
</main>
89
)
910
}

src/config/database.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { createClient } from '@supabase/supabase-js';
2+
3+
// Substitua pelos valores reais da sua instância Supabase
4+
const SUPABASE_URL = process.env.SUPABASE_URL; // URL da sua instância do Supabase
5+
const SUPABASE_ANON_KEY = process.env.SUPABASE_KEY; // Chave pública anônima (encontrada no painel do Supabase)
6+
7+
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
8+
export default supabase

src/models/Post.ts

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import supabase from "../config/database"; // Caminho para o seu cliente Supabase
2+
3+
interface Post {
4+
id: string;
5+
title: string;
6+
desc: string;
7+
date: string; // O Supabase geralmente lida com datas como strings em formato ISO
8+
}
9+
10+
class PostModel {
11+
// Função para obter todos os posts
12+
static async getAllPosts(): Promise<Post[]> {
13+
const { data, error } = await supabase
14+
.from("posts")
15+
.select("*");
16+
17+
if (error) {
18+
throw new Error(error.message);
19+
}
20+
21+
return data as Post[];
22+
}
23+
24+
// Função para criar um novo post
25+
static async createPost(title: string, desc: string): Promise<Post> {
26+
const { data, error } = await supabase
27+
.from("posts")
28+
.insert([{ title, desc, date: new Date().toISOString() }])
29+
.single();
30+
31+
if (error) {
32+
throw new Error(error.message);
33+
}
34+
35+
return data as Post;
36+
}
37+
38+
// Função para obter um post por ID
39+
static async getPostById(postId: string): Promise<Post | null> {
40+
const { data, error } = await supabase
41+
.from("posts")
42+
.select("*")
43+
.eq("id", postId)
44+
.single();
45+
46+
if (error) {
47+
throw new Error(error.message);
48+
}
49+
50+
return data as Post | null;
51+
}
52+
53+
// Função para atualizar um post
54+
static async updatePost(postId: string, title: string, desc: string): Promise<Post> {
55+
const { data, error } = await supabase
56+
.from("posts")
57+
.update({ title, desc })
58+
.eq("id", postId)
59+
.single();
60+
61+
if (error) {
62+
throw new Error(error.message);
63+
}
64+
65+
return data as Post;
66+
}
67+
68+
// Função para deletar um post
69+
static async deletePost(postId: string): Promise<void> {
70+
const { error } = await supabase
71+
.from("posts")
72+
.delete()
73+
.eq("id", postId);
74+
75+
if (error) {
76+
throw new Error(error.message);
77+
}
78+
}
79+
}
80+
81+
export default PostModel;

tsconfig.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
{
22
"compilerOptions": {
3+
"noImplicitAny": false,
34
"target": "es5",
45
"lib": ["dom", "dom.iterable", "esnext"],
56
"allowJs": true,
67
"skipLibCheck": true,
7-
"strict": true,
8+
"strict": false,
89
"noEmit": true,
910
"esModuleInterop": true,
1011
"module": "esnext",

0 commit comments

Comments
 (0)