diff --git a/src/app/api/posts/route.ts b/src/app/api/posts/route.ts index e0841b4..b5825ef 100644 --- a/src/app/api/posts/route.ts +++ b/src/app/api/posts/route.ts @@ -3,7 +3,7 @@ import { NextResponse } from "next/server" export const GET = async (req: Request) => { try { - // Aguarda a resolução da promessa + const posts = await getPosts(); return NextResponse.json({ message: 'OK', posts }, { status: 200 }); @@ -22,7 +22,7 @@ export const POST = async (req: Request) => { try { const post = { title, slug, author_id }; - await addPost(post); // Garantir que a função addPost aguarde a inserção do post + await addPost(post); return NextResponse.json({ message: "Ok", post }, { status: 201 }); } catch (err) { if (err instanceof Error) { diff --git a/src/app/api/users/route.ts b/src/app/api/users/route.ts index 5a92ce0..1834176 100644 --- a/src/app/api/users/route.ts +++ b/src/app/api/users/route.ts @@ -3,7 +3,7 @@ import { NextResponse } from "next/server" export const GET = async (req: Request) => { try { - // Aguarda a resolução da promessa + const users = await getUsers(); return NextResponse.json({ message: 'OK', users }, { status: 200 }); @@ -22,7 +22,7 @@ export const POST = async (req: Request) => { try { const user = { username, email, password, is_admin }; - await addUser(user); // Garantir que a função addPost aguarde a inserção do post + await addUser(user); return NextResponse.json({ message: "Ok", user }, { status: 201 }); } catch (err) { if (err instanceof Error) { diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 73c0a4b..e8abbc5 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -4,7 +4,7 @@ import { Inter } from 'next/font/google' const inter = Inter({ subsets: ['latin'] }) export const metadata: Metadata = { - title: 'Create Next App', + title: 'posts-api-vercel', description: 'Generated by create next app', } diff --git a/src/app/lib/posts_controller.ts b/src/app/lib/posts_controller.ts index 2e7b701..dc5ef1e 100644 --- a/src/app/lib/posts_controller.ts +++ b/src/app/lib/posts_controller.ts @@ -1,17 +1,12 @@ -import supabase from '../../config/database'; // Importando o cliente Supabase +import { UserInput } from '@/models/models'; +import supabase from '../../config/database'; + -export interface UserInput{ - id?: string - title: string - slug: string - author_id: number -} -// Obter todos os posts export const getPosts = async () => { const { data, error } = await supabase - .from('posts') // Nome da tabela - .select('*'); // Seleciona todos os campos + .from('posts') + .select('*'); console.log(data) @@ -19,10 +14,10 @@ export const getPosts = async () => { return data; }; -// Adicionar um novo post + export const addPost = async ({title, slug, author_id}:UserInput) => { const { data, error } = await supabase - .from('posts') // Nome da tabela + .from('posts') .insert([ {title, slug, author_id } ]); @@ -31,12 +26,12 @@ export const addPost = async ({title, slug, author_id}:UserInput) => { return data; }; -// Deletar um post pelo id + export const deletePost = async (id: string) => { const { data, error } = await supabase .from('posts') .delete() - .eq('id', id); // A condição de deletar pelo id + .eq('id', id); if (error) throw new Error(error.message); if (!data) { @@ -47,25 +42,25 @@ export const deletePost = async (id: string) => { return data; }; -// Atualizar um post pelo id + export const updatePost = async ({id, title, slug, author_id}:UserInput) => { const { data, error } = await supabase .from('posts') .update({ title, slug, author_id }) - .eq('id', id); // A condição de atualizar pelo id + .eq('id', id); if (error) throw new Error(error.message); if (!data) throw new Error("NO POST FOUND"); return data; }; -// Obter um post pelo id + export const getPostById = async (id: string) => { const { data, error } = await supabase .from('posts') .select('*') .eq('id', id) - .single(); // Para pegar apenas um resultado (usamos .single() para retornar um único item) + .single(); if (error) throw new Error(error.message); if (!data) throw new Error("NO POST FOUND"); diff --git a/src/app/lib/users_controller.ts b/src/app/lib/users_controller.ts index a1858f1..273db56 100644 --- a/src/app/lib/users_controller.ts +++ b/src/app/lib/users_controller.ts @@ -1,17 +1,11 @@ -import supabase from '../../config/database'; // Importando o cliente Supabase +import { UserInputProps } from '@/models/models'; +import supabase from '../../config/database'; + -interface UserInputProps{ - id?:number | string - username: string - email: string - password: string - is_admin: boolean -} -// Obter todos os posts export const getUsers = async () => { const { data, error } = await supabase - .from('users') // Nome da tabela - .select('*'); // Seleciona todos os campos + .from('users') + .select('*'); console.log(data) @@ -19,10 +13,10 @@ export const getUsers = async () => { return data; }; -// Adicionar um novo post + export const addUser = async ({username, password, is_admin, email}:UserInputProps) => { const { data, error } = await supabase - .from('users') // Nome da tabela + .from('users') .insert([ {username, password, is_admin, email} ]); @@ -31,13 +25,12 @@ export const addUser = async ({username, password, is_admin, email}:UserInputPro return data; }; -// Deletar um post pelo id + export const deleteUser = async (id: string) => { const { data, error } = await supabase .from('users') .delete() - .eq('id', id); // A condição de deletar pelo id - + .eq('id', id); if (error) throw new Error(error.message); if (!data) { throw new Error("NO USER FOUND"); @@ -47,19 +40,19 @@ export const deleteUser = async (id: string) => { return data; }; -// Atualizar um post pelo id + export const updateUser = async ({username, password, is_admin, email, id}:UserInputProps) => { const { data, error } = await supabase .from('users') .update({ username, email, password, is_admin }) - .eq('id', id); // A condição de atualizar pelo id + .eq('id', id); if (error) throw new Error(error.message); if (!data) throw new Error("NO USER FOUND"); return data; }; -// Obter um post pelo id + export const getUserById = async (id: string) => { console.log(id); @@ -67,7 +60,7 @@ export const getUserById = async (id: string) => { .from('users') .select('*') .eq('id', id) - .single(); // Para pegar apenas um resultado (usamos .single() para retornar um único item) + .single(); if (error) throw new Error(error.message); diff --git a/src/models/Post.ts b/src/models/Post.ts deleted file mode 100644 index 889baf5..0000000 --- a/src/models/Post.ts +++ /dev/null @@ -1,81 +0,0 @@ -import supabase from "../config/database"; // Caminho para o seu cliente Supabase - -interface Post { - id: string; - title: string; - desc: string; - date: string; // O Supabase geralmente lida com datas como strings em formato ISO -} - -class PostModel { - // Função para obter todos os posts - static async getAllPosts(): Promise { - const { data, error } = await supabase - .from("posts") - .select("*"); - - if (error) { - throw new Error(error.message); - } - - return data as Post[]; - } - - // Função para criar um novo post - static async createPost(title: string, desc: string): Promise { - const { data, error } = await supabase - .from("posts") - .insert([{ title, desc, date: new Date().toISOString() }]) - .single(); - - if (error) { - throw new Error(error.message); - } - - return data as Post; - } - - // Função para obter um post por ID - static async getPostById(postId: string): Promise { - const { data, error } = await supabase - .from("posts") - .select("*") - .eq("id", postId) - .single(); - - if (error) { - throw new Error(error.message); - } - - return data as Post | null; - } - - // Função para atualizar um post - static async updatePost(postId: string, title: string, desc: string): Promise { - const { data, error } = await supabase - .from("posts") - .update({ title, desc }) - .eq("id", postId) - .single(); - - if (error) { - throw new Error(error.message); - } - - return data as Post; - } - - // Função para deletar um post - static async deletePost(postId: string): Promise { - const { error } = await supabase - .from("posts") - .delete() - .eq("id", postId); - - if (error) { - throw new Error(error.message); - } - } -} - -export default PostModel; diff --git a/src/models/User.ts b/src/models/User.ts deleted file mode 100644 index d2cf613..0000000 --- a/src/models/User.ts +++ /dev/null @@ -1,88 +0,0 @@ -import supabase from "../config/database"; // Caminho para o seu cliente Supabase - -interface User { - id: string; - username: string; - password: string; - createsAt: Date; - is_admin: boolean; -} - -interface UserInputProps { - username: string; - password: string; - is_admin: boolean; -} - -class UserModel { - // Função para obter todos os usuários - static async getAllUsers(): Promise { - const { data, error } = await supabase - .from("users") - .select("*"); - - if (error) { - throw new Error(error.message); - } - - return data as User[]; - } - - // Função para criar um novo usuário - static async createUser({ username, password, is_admin }: UserInputProps): Promise { - const { data, error } = await supabase - .from("users") - .insert([{ username, password, is_admin }]) - .single(); - - if (error) { - throw new Error(error.message); - } - - return data as User; - } - - // Função para obter um usuário por ID - static async getUserById(userId: string): Promise { - const { data, error } = await supabase - .from("users") - .select("*") - .eq("id", userId) - .single(); - - if (error) { - throw new Error(error.message); - } - - return data as User | null; - } - - // Função para atualizar um usuário - static async updateUser(userId: string, { username, password, is_admin }: UserInputProps): Promise { - const { data, error } = await supabase - .from("users") - .update({ username, password, is_admin }) - .eq("id", userId) - .single(); - - if (error) { - throw new Error(error.message); - } - - return data as User; - } - - // Função para deletar um usuário - static async deleteUser(userId: string): Promise { - const { error } = await supabase - .from("users") - .delete() - .eq("id", userId); - - if (error) { - throw new Error(error.message); - } - } -} - -export default UserModel; diff --git a/src/models/models.ts b/src/models/models.ts new file mode 100644 index 0000000..cc4cbb8 --- /dev/null +++ b/src/models/models.ts @@ -0,0 +1,15 @@ +export interface UserInput{ + id?: string + title: string + slug: string + author_id: number +} + + +export interface UserInputProps{ + id?:number | string + username: string + email: string + password: string + is_admin: boolean +} \ No newline at end of file