From aa6b384480ca96696a7c8b4d48d86af336db7b10 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Sun, 29 Jan 2023 16:24:19 -0300 Subject: [PATCH 01/22] Feat: se aplicado, este commit adicionara endpoints createUser createPost --- .gitignore | 4 +++ package.json | 28 +++++++++++++++++++++ request.rest | 37 ++++++++++++++++++++++++++++ src/dataBase/connection.ts | 18 ++++++++++++++ src/dataBase/migrations.ts | 41 +++++++++++++++++++++++++++++++ src/endpoints/createFriendship.ts | 27 ++++++++++++++++++++ src/endpoints/createPost.ts | 29 ++++++++++++++++++++++ src/endpoints/createUser.ts | 33 +++++++++++++++++++++++++ src/endpoints/getPosts.ts | 37 ++++++++++++++++++++++++++++ src/index.ts | 27 ++++++++++++++++++++ src/models/Posts.ts | 13 ++++++++++ src/models/User.ts | 11 +++++++++ tsconfig.json | 11 +++++++++ 13 files changed, 316 insertions(+) create mode 100644 .gitignore create mode 100644 package.json create mode 100644 request.rest create mode 100644 src/dataBase/connection.ts create mode 100644 src/dataBase/migrations.ts create mode 100644 src/endpoints/createFriendship.ts create mode 100644 src/endpoints/createPost.ts create mode 100644 src/endpoints/createUser.ts create mode 100644 src/endpoints/getPosts.ts create mode 100644 src/index.ts create mode 100644 src/models/Posts.ts create mode 100644 src/models/User.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8ece3ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules +package-lock.json +build +.env \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..7f39e91 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "revisao-full-stack", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "tsc && node ./build/index.js", + "dev": "ts-node-dev ./src/index.ts", + "migrations": "tsc && node ./build/dataBase/migrations.js" + }, + "author": "Byron", + "license": "ISC", + "dependencies": { + "@types/node": "^18.11.18", + "dotenv": "^16.0.3", + "express": "^4.18.2", + "knex": "^2.4.0", + "mysql": "^2.18.1", + "typescript": "^4.9.4" + }, + "devDependencies": { + "@types/cors": "^2.8.13", + "@types/express": "^4.17.15", + "@types/knex": "^0.16.1", + "cors": "^2.8.5", + "ts-node-dev": "^2.0.0" + } +} diff --git a/request.rest b/request.rest new file mode 100644 index 0000000..4965eb8 --- /dev/null +++ b/request.rest @@ -0,0 +1,37 @@ + +### Create a new Client +POST http://localhost:3003/users +Content-Type: application/json + +{ + "name":"Dany Smith", + "email":"dany@gmail.com", + "password": "1234567" +} + +### Return all post +GET http://localhost:3003/posts/1675001631299 +Content-Type: application/json + +### Return stock +POST http://localhost:3003/post +Content-Type: application/json + +{ + "photo" : "Foto", + "description": "foto da viagem", + "type": "normal", + "created_at": "" , + "authorId": "1675001631299" +} + +### + +POST http://localhost:3003/friendship +Content-Type: application/json + +{ + "friend":"1675019596015", + "authorId": "1675001631299" +} + diff --git a/src/dataBase/connection.ts b/src/dataBase/connection.ts new file mode 100644 index 0000000..db29f16 --- /dev/null +++ b/src/dataBase/connection.ts @@ -0,0 +1,18 @@ +import knex from "knex" +import dotenv from "dotenv"; + +dotenv.config(); + +const connection = knex({ + client: "mysql", + connection: { + host: process.env.DB_HOST, + port: 3306, + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_DATABASE, + multipleStatements: true + }, +}); + +export default connection \ No newline at end of file diff --git a/src/dataBase/migrations.ts b/src/dataBase/migrations.ts new file mode 100644 index 0000000..d3bf210 --- /dev/null +++ b/src/dataBase/migrations.ts @@ -0,0 +1,41 @@ +import connection from "./connection" +const createTables = async () => { + await connection.raw(` + CREATE TABLE IF NOT EXISTS labook_users( + id VARCHAR(255) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + password VARCHAR(255) NOT NULL + ); + + CREATE TABLE IF NOT EXISTS labook_posts( + id VARCHAR(255) PRIMARY KEY, + photo VARCHAR(255) NOT NULL, + description VARCHAR(255) NOT NULL, + type ENUM("normal","event") DEFAULT "normal", + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + author_id VARCHAR(255), + FOREIGN KEY (author_id) REFERENCES labook_users (id) + ) + + CREATE TABLE IF NOT EXISTS labook_friendship( + id VARCHAR(255) PRIMARY KEY, + friend_id VARCHAR(255) NOT NULL, + author_id VARCHAR(255), + FOREIGN KEY (author_id) REFERENCES labook_users (id), + FOREIGN KEY (friend_id) REFERENCES labook_users (id) + ) + + `) + .then(() => { + console.log(`Tables created successfully!`) + + }) + .catch((error: any) => printError(error)) +} + +const printError = (error: any) => { + console.log(error.sqlMessage || error.message) +} + +createTables() diff --git a/src/endpoints/createFriendship.ts b/src/endpoints/createFriendship.ts new file mode 100644 index 0000000..487fad9 --- /dev/null +++ b/src/endpoints/createFriendship.ts @@ -0,0 +1,27 @@ +import { Request, Response } from "express"; +import connection from "../dataBase/connection"; +export const createFriendship = async (req: Request, res: Response) => { + try { + let message = "Success!" + + const { friend, authorId } = req.body + console.log(); + + + const friendship: string = Date.now().toString() + + await connection("labook_friendship") + .insert({ + id:friendship, + friend_id: friend, + author_id: authorId + }) + + res.status(201).send({ message }) + + } catch (error:any) { + let message = error.sqlMessage || error.message + res.statusCode = 400 + res.send({ message }) + } + } \ No newline at end of file diff --git a/src/endpoints/createPost.ts b/src/endpoints/createPost.ts new file mode 100644 index 0000000..0174e31 --- /dev/null +++ b/src/endpoints/createPost.ts @@ -0,0 +1,29 @@ +import { Request, Response } from "express"; +import connection from "../dataBase/connection"; +export const createPost = async (req: Request, res: Response) => { + try { + let message = "Success!" + + const { photo, description, type, authorId } = req.body + console.log(); + + + const postId: string = Date.now().toString() + + await connection("labook_posts") + .insert({ + id:postId, + photo, + description, + type, + author_id: authorId + }) + + res.status(201).send({ message }) + + } catch (error:any) { + let message = error.sqlMessage || error.message + res.statusCode = 400 + res.send({ message }) + } + } \ No newline at end of file diff --git a/src/endpoints/createUser.ts b/src/endpoints/createUser.ts new file mode 100644 index 0000000..87c4308 --- /dev/null +++ b/src/endpoints/createUser.ts @@ -0,0 +1,33 @@ +import { Request, Response } from "express"; +import connection from "../dataBase/connection"; +export const createUser =async (req: Request, res: Response) => { + let errorCode = 400; + try{ + let message = "Success!" + const { name, email, password } = req.body + + if (!name || !email || !password) { + res.statusCode = 406 + message = '"name", "email" and "password" must be provided' + throw new Error(message) + } + + const id: string = Date.now().toString() + + await connection('labook_users') + .insert({ + id, + name, + email, + password + }) + + res.status(201).send({ message }) + + } catch (error:any) { + res.statusCode = 400 + let message = error.sqlMessage || error.message + res.send({ message }) + } + +} \ No newline at end of file diff --git a/src/endpoints/getPosts.ts b/src/endpoints/getPosts.ts new file mode 100644 index 0000000..0105693 --- /dev/null +++ b/src/endpoints/getPosts.ts @@ -0,0 +1,37 @@ +import { Request, Response } from "express"; +import connection from "../dataBase/connection"; +import { TPost } from "../models/Posts"; +export const getPost = async (req: Request, res: Response) => { + try { + let message = "Success!" + + const { id } = req.params + + const queryResult: any = await connection("labook_posts") + .select("*") + .where({ author_id: id }) + + + if (!queryResult[0]) { + res.statusCode = 404 + message = "Post not found" + throw new Error(message) + } + + const post: TPost = { + id: queryResult[0].id, + photo: queryResult[0].photo, + description: queryResult[0].description, + type: queryResult[0].type, + createdAt: queryResult[0].created_at, + authorId: queryResult[0].author_id, + } + + res.status(200).send({ message, post }) + + } catch (error:any) { + let message = error.sqlMessage || error.message + res.statusCode = 400 + res.send({ message }) + } + } \ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..ef08585 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,27 @@ +import express, { Express, Request, Response } from "express" +import cors from "cors" +import { createUser } from "./endpoints/createUser" +import { createPost } from "./endpoints/createPost" +import { getPost } from "./endpoints/getPosts" +import { createFriendship } from "./endpoints/createFriendship" + +/**************************** CONFIG ******************************/ + +const app: Express = express() +app.use(express.json()) +app.use(cors()) + +app.listen(3003, () => { + console.log("Server running on port 3003") +}) + + +/**************************** ENDPOINTS ******************************/ +app.post('/users',createUser); + +app.post('/post',createPost); + +app.post('/friendship',createFriendship); + +app.get('/posts/:id',getPost); + diff --git a/src/models/Posts.ts b/src/models/Posts.ts new file mode 100644 index 0000000..e79fe19 --- /dev/null +++ b/src/models/Posts.ts @@ -0,0 +1,13 @@ +enum TPOST_TYPES { + NORMAL = "normal", + EVENT = "event" + } + + export type TPost = { + id: string, + photo: string, + description: string, + type: TPOST_TYPES, + createdAt: Date, + authorId: string + } \ No newline at end of file diff --git a/src/models/User.ts b/src/models/User.ts new file mode 100644 index 0000000..9a7a3d4 --- /dev/null +++ b/src/models/User.ts @@ -0,0 +1,11 @@ +export type authenticationData = { + id: string + } + +export type TUser = { + id: string, + name: string, + email: string, + password: string + } + \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..a9ee948 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, + "outDir": "./build" /* Redirect output structure to the directory. */, + "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */, + "strict": true /* Enable all strict type-checking options. */, + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +} \ No newline at end of file From 31f2df356f0f1cb3bf7fced8443afc13da803c3e Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Mon, 30 Jan 2023 09:51:12 -0300 Subject: [PATCH 02/22] Feat: se aplicado, este commit add os endPoints createFriendship, deleteFriendship e getFriendships --- request.rest | 25 +++++++++++---- src/endpoints/deleteFriendship.ts | 33 ++++++++++++++++++++ src/endpoints/getFriendships.ts | 52 +++++++++++++++++++++++++++++++ src/index.ts | 6 ++++ src/models/Friendship.ts | 6 ++++ src/models/friends.ts | 5 +++ 6 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 src/endpoints/deleteFriendship.ts create mode 100644 src/endpoints/getFriendships.ts create mode 100644 src/models/Friendship.ts create mode 100644 src/models/friends.ts diff --git a/request.rest b/request.rest index 4965eb8..d10208f 100644 --- a/request.rest +++ b/request.rest @@ -1,11 +1,11 @@ -### Create a new Client +### Create a new User POST http://localhost:3003/users Content-Type: application/json { - "name":"Dany Smith", - "email":"dany@gmail.com", + "name":"Bianca Smith", + "email":"bianca@gmail.com", "password": "1234567" } @@ -13,7 +13,7 @@ Content-Type: application/json GET http://localhost:3003/posts/1675001631299 Content-Type: application/json -### Return stock +### Create a new Post POST http://localhost:3003/post Content-Type: application/json @@ -25,13 +25,26 @@ Content-Type: application/json "authorId": "1675001631299" } -### +### Create a new Friendship POST http://localhost:3003/friendship Content-Type: application/json { - "friend":"1675019596015", + "friend":"1675081679184", "authorId": "1675001631299" } +### Delete Friendship + +DELETE http://localhost:3003/friendship/1675001631299 +Content-Type: application/json + +{ + "friend":"1675081679184" +} + +### Return all Friend +GET http://localhost:3003/friendship/1675001631299 +Content-Type: application/json + diff --git a/src/endpoints/deleteFriendship.ts b/src/endpoints/deleteFriendship.ts new file mode 100644 index 0000000..1ea2351 --- /dev/null +++ b/src/endpoints/deleteFriendship.ts @@ -0,0 +1,33 @@ +import { Request, Response } from "express"; +import connection from "../dataBase/connection"; +import { TFriendship } from "../models/Friendship"; +export const deleteFriendships = async (req: Request, res: Response) => { + try { + let message = "Success!" + + const { id } = req.params + const {friend} = req.body + + const queryResult: TFriendship[] = await connection("labook_friendship") + .select("*") + .where({ author_id: id, friend_id: friend }) + + + if (!queryResult[0]) { + res.statusCode = 404 + message = "friend not found" + throw new Error(message) + } + + const queryDelete: any = await connection("labook_friendship") + .where({ author_id: id, friend_id: friend }) + .del() + + res.status(200).send({ message }) + + } catch (error:any) { + let message = error.sqlMessage || error.message + res.statusCode = 400 + res.send({ message }) + } + } \ No newline at end of file diff --git a/src/endpoints/getFriendships.ts b/src/endpoints/getFriendships.ts new file mode 100644 index 0000000..2417db2 --- /dev/null +++ b/src/endpoints/getFriendships.ts @@ -0,0 +1,52 @@ +import { Request, Response } from "express"; +import connection from "../dataBase/connection"; +import { TFriends } from "../models/friends"; +import { TFriendship } from "../models/Friendship"; +import { TUser } from "../models/User"; +export const getFriendships = async (req: Request, res: Response) => { + try { + let message = "Success!"; + + const { id } = req.params; + + if (!id) { + res.statusCode = 404; + message = "id obrigation"; + throw new Error(message); + } + + const queryResult: TFriendship[] = await connection("labook_friendship") + .select("*") + .where({ author_id: id }); + + if (!queryResult[0]) { + res.statusCode = 404; + message = "friendship not found"; + throw new Error(message); + } + + let friends:TFriends[] = []; + for (let i = 0; i < queryResult.length; i++) { + const queryUser:TUser[] = await connection("labook_users") + .select("*") + .where({ id: queryResult[i].friend_id }); + + if (!queryUser[0]) { + res.statusCode = 404; + message = "friendship not found"; + throw new Error(message); + } else { + friends.push({ + friend_id: queryUser[0].id, + name: queryUser[0].name, + }); + } + } + + res.status(200).send({ message, friends }); + } catch (error: any) { + let message = error.sqlMessage || error.message; + res.statusCode = 400; + res.send({ message }); + } +}; diff --git a/src/index.ts b/src/index.ts index ef08585..7e730a6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,8 @@ import { createUser } from "./endpoints/createUser" import { createPost } from "./endpoints/createPost" import { getPost } from "./endpoints/getPosts" import { createFriendship } from "./endpoints/createFriendship" +import { getFriendships } from "./endpoints/getFriendships" +import { deleteFriendships } from "./endpoints/deleteFriendship" /**************************** CONFIG ******************************/ @@ -23,5 +25,9 @@ app.post('/post',createPost); app.post('/friendship',createFriendship); +app.delete('/friendship/:id',deleteFriendships); + app.get('/posts/:id',getPost); +app.get('/friendship/:id',getFriendships); + diff --git a/src/models/Friendship.ts b/src/models/Friendship.ts new file mode 100644 index 0000000..d0a7120 --- /dev/null +++ b/src/models/Friendship.ts @@ -0,0 +1,6 @@ +export type TFriendship = { + id: string, + friend_id: string, + author: string + +} \ No newline at end of file diff --git a/src/models/friends.ts b/src/models/friends.ts new file mode 100644 index 0000000..00e114e --- /dev/null +++ b/src/models/friends.ts @@ -0,0 +1,5 @@ +export type TFriends = { + friend_id: string, + name: string + +} \ No newline at end of file From 6a8bc2b89189abdb1518cbaf0f869e9948990754 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Mon, 30 Jan 2023 09:55:02 -0300 Subject: [PATCH 03/22] Update README.md --- README.md | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/README.md b/README.md index 49352af..6511415 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,67 @@ # labook-template Repositório do projeto Labook + +##

📇 Labook

+ +## :memo: Descrição +Projeto desenvolvido como didática de back-end para as turmas JBL LABENU com conteúdos que englobam o universo da criação de uma API com a temática de um sistema de gerenciamento básico da organizaçãode labenu. + +## Link Documentação Postman +[Doc_Postman](https://documenter.getpostman.com/view/22363157/2s8Z75S9p9) + +## Link Deploy Render +https://labsystem6.onrender.com + +## 👩🏾Pessoas Desenvolvedoras do Projeto + +| [
Ricardo Barros](https://github.com/Ricardoteleco) | [
Byron Smith](https://github.com/byron-smith-nobrega) | [
Jéssica Lima](https://github.com/jessicalimaz) | +| :---: | :---: | :---: | + +## :books: Funcionalidades +* Criar Estudantes: Métodos voltados para a criação de usuários que são estudantes. +* Buscar Estudantes: Métodos voltados para a consulta de estudantes cadastradas. +* Mudar Estudantes de Turma: Métodos voltados para a alteração do estudante de turma. +* Criar Docentes: Métodos voltados para a criação de usuários que são pessoas instrutora. +* Buscar Docentes: Métodos voltados para a consulta de pessoas instrutoras cadastradas. +* Mudar Docente de Turma: Métodos voltados para a alteração do docente de turma. +* Criar Turma: Métodos para a criação de turmas. +* Buscar Turma: Métodos que realiza busca em banco das turmas ativas. +* Mudar Turma Módulo: Métodos voltados para a alteração da turma de mód. + + +## :wrench: Tecnologias utilizadas +* VS Code +* nodeJS +* expressJS +* axios +* cors +* dotenv +* MySQL + + +## :rocket: Rodando o projeto +Para rodar o repositório é necessário clonar o mesmo, dar o seguinte comando para instalar as dependências: +``` +npm install +``` +Após instaladas as dependências, configure o arquivo .env: +``` +DB_HOST = +DB_USER = "" +DB_PASS = "" +DB_NAME = "" +``` +Após configuração do .env, dê o comando seguinte para rodar o migration: +``` +npm run migrations +``` +Após o migration, dê o comando seguinte para rodar a aplicação: +``` +npm run start +``` + +Use o Postman ou o Insomnia para realizar as requisições desejadas. + +## :dart: Status do projeto +O projeto está em andamento. + From 8bab786f86eecd99795118d519563a78bced3181 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Mon, 30 Jan 2023 09:57:37 -0300 Subject: [PATCH 04/22] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 6511415..05f3929 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,7 @@ https://labsystem6.onrender.com ## 👩🏾Pessoas Desenvolvedoras do Projeto -| [
Ricardo Barros](https://github.com/Ricardoteleco) | [
Byron Smith](https://github.com/byron-smith-nobrega) | [
Jéssica Lima](https://github.com/jessicalimaz) | -| :---: | :---: | :---: | + [
Byron Smith](https://github.com/byron-smith-nobrega) ## :books: Funcionalidades * Criar Estudantes: Métodos voltados para a criação de usuários que são estudantes. From 8fde5ce4365c944eda63e9cc884fec20943ba5fd Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Thu, 2 Feb 2023 20:02:38 -0300 Subject: [PATCH 05/22] Refactor: se aplicado, este commit coloca o projeto na arquitetura de 3 camadas --- package.json | 4 +- request.rest | 48 +++++--- src/business/FriendshipBusiness.ts | 106 +++++++++++++++++ src/business/LikeBusiness.ts | 107 +++++++++++++++++ src/business/PostBusiness.ts | 155 +++++++++++++++++++++++++ src/business/UserBusiness.ts | 42 +++++++ src/controller/FriendshipController.ts | 37 ++++++ src/controller/LikeController.ts | 36 ++++++ src/controller/PostController.ts | 69 +++++++++++ src/controller/UserController.ts | 24 ++++ src/data/BaseDatabase.ts | 17 +++ src/data/FriendshipDatabase.ts | 67 +++++++++++ src/data/LikeDatabase.ts | 47 ++++++++ src/data/PostDatabase.ts | 69 +++++++++++ src/data/UserDatabase.ts | 41 +++++++ src/{dataBase => data}/connection.ts | 4 +- src/{dataBase => data}/migrations.ts | 2 +- src/endpoints/createFriendship.ts | 27 ----- src/endpoints/createPost.ts | 29 ----- src/endpoints/createUser.ts | 33 ------ src/endpoints/deleteFriendship.ts | 33 ------ src/endpoints/getFriendships.ts | 52 --------- src/endpoints/getPosts.ts | 37 ------ src/index.ts | 35 +++--- src/model/Friendship.ts | 24 ++++ src/model/Posts.ts | 45 +++++++ src/{models => model}/User.ts | 0 src/model/friends.ts | 10 ++ src/model/likes.ts | 21 ++++ src/models/Friendship.ts | 6 - src/models/Posts.ts | 13 --- src/models/friends.ts | 5 - src/service/formatDate.ts | 13 +++ 33 files changed, 993 insertions(+), 265 deletions(-) create mode 100644 src/business/FriendshipBusiness.ts create mode 100644 src/business/LikeBusiness.ts create mode 100644 src/business/PostBusiness.ts create mode 100644 src/business/UserBusiness.ts create mode 100644 src/controller/FriendshipController.ts create mode 100644 src/controller/LikeController.ts create mode 100644 src/controller/PostController.ts create mode 100644 src/controller/UserController.ts create mode 100644 src/data/BaseDatabase.ts create mode 100644 src/data/FriendshipDatabase.ts create mode 100644 src/data/LikeDatabase.ts create mode 100644 src/data/PostDatabase.ts create mode 100644 src/data/UserDatabase.ts rename src/{dataBase => data}/connection.ts (87%) rename src/{dataBase => data}/migrations.ts (96%) delete mode 100644 src/endpoints/createFriendship.ts delete mode 100644 src/endpoints/createPost.ts delete mode 100644 src/endpoints/createUser.ts delete mode 100644 src/endpoints/deleteFriendship.ts delete mode 100644 src/endpoints/getFriendships.ts delete mode 100644 src/endpoints/getPosts.ts create mode 100644 src/model/Friendship.ts create mode 100644 src/model/Posts.ts rename src/{models => model}/User.ts (100%) create mode 100644 src/model/friends.ts create mode 100644 src/model/likes.ts delete mode 100644 src/models/Friendship.ts delete mode 100644 src/models/Posts.ts delete mode 100644 src/models/friends.ts create mode 100644 src/service/formatDate.ts diff --git a/package.json b/package.json index 7f39e91..2e0e6ce 100644 --- a/package.json +++ b/package.json @@ -16,12 +16,14 @@ "express": "^4.18.2", "knex": "^2.4.0", "mysql": "^2.18.1", - "typescript": "^4.9.4" + "typescript": "^4.9.4", + "uuid": "^9.0.0" }, "devDependencies": { "@types/cors": "^2.8.13", "@types/express": "^4.17.15", "@types/knex": "^0.16.1", + "@types/uuid": "^9.0.0", "cors": "^2.8.5", "ts-node-dev": "^2.0.0" } diff --git a/request.rest b/request.rest index d10208f..4ae4ee5 100644 --- a/request.rest +++ b/request.rest @@ -4,13 +4,13 @@ POST http://localhost:3003/users Content-Type: application/json { - "name":"Bianca Smith", - "email":"bianca@gmail.com", + "name":"Bianca2 Smith", + "email":"bianca2@gmail.com", "password": "1234567" } -### Return all post -GET http://localhost:3003/posts/1675001631299 +### Return post +GET http://localhost:3003/posts/1675017838548 Content-Type: application/json ### Create a new Post @@ -20,31 +20,53 @@ Content-Type: application/json { "photo" : "Foto", "description": "foto da viagem", - "type": "normal", - "created_at": "" , - "authorId": "1675001631299" + "type": "event", + "createdAt": "02/01/2023", + "authorId": "1675081697628" } ### Create a new Friendship - POST http://localhost:3003/friendship Content-Type: application/json { - "friend":"1675081679184", + "friendId":"1675081679184", "authorId": "1675001631299" } ### Delete Friendship - DELETE http://localhost:3003/friendship/1675001631299 Content-Type: application/json { - "friend":"1675081679184" + "friendId":"1675081679184" } -### Return all Friend -GET http://localhost:3003/friendship/1675001631299 +### Return Feeds friends +GET http://localhost:3003/feeds/1675001631299 +Content-Type: application/json + +### return feed by type +GET http://localhost:3003/feeds Content-Type: application/json +{ + "type":"event" +} + +### Like Post +POST http://localhost:3003/like +Content-Type: application/json + +{ + "postId":"1675089703154", + "authorId": "1675001631299" +} + +### Delete Like Post +DELETE http://localhost:3003/like/1675001631299 +Content-Type: application/json + +{ + "postId":"1675089703154" +} \ No newline at end of file diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts new file mode 100644 index 0000000..4699e03 --- /dev/null +++ b/src/business/FriendshipBusiness.ts @@ -0,0 +1,106 @@ +import { FriendshipDatabase } from "../data/FriendshipDatabase"; +import { UserDatabase } from "../data/UserDatabase"; +import { FriendInputDTO } from "../model/friends"; +import { + DeleteFriendshipInputDTO, + FriendshipInputDTO, + TFriendship, +} from "../model/Friendship"; + +const friendshipDatabase = new FriendshipDatabase(); +const userDatabase = new UserDatabase(); + +export class FriendshipBusiness { + createFriendship = async (input: FriendInputDTO): Promise => { + try { + const { friendId, authorId } = input; + + if (!friendId || !authorId) { + throw new Error("Fill in the friendId, authorId fields"); + } + + const queryUser = await userDatabase.findUser(); + const existFriend = queryUser.findIndex((user) => { + return user.id === friendId; + }); + + if (existFriend === -1) { + throw new Error("Friend id does not exist."); + } + + const existauthorId = queryUser.findIndex((user) => { + return user.id === authorId; + }); + + if (existauthorId === -1) { + throw new Error("User id does not exist."); + } + + const id: string = Date.now().toString(); + + const queryResult: FriendshipInputDTO[] = + await friendshipDatabase.findFriendship(authorId); + + const existFriendship = queryResult.findIndex((user) => { + return user.friend_id === friendId; + }); + + if (existFriendship != -1) { + throw new Error("friendship already exists!"); + } + const idFriend: string = Date.now().toString(); + + await friendshipDatabase.insertPost({ + id, + idRows: idFriend, + friendId, + authorId, + }); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findFriendship = () => {}; + + deleteFriendship = async (input: DeleteFriendshipInputDTO): Promise => { + try { + const { friendId, authorId } = input; + + if (!friendId || !authorId) { + throw new Error("Fill in the friendId, authorId fields"); + } + + const queryUser = await userDatabase.findUser(); + const existFriend = queryUser.findIndex((user) => { + return user.id === friendId; + }); + + if (existFriend === -1) { + throw new Error("Friend id does not exist."); + } + + const existauthorId = queryUser.findIndex((user) => { + return user.id === authorId; + }); + + if (existauthorId === -1) { + throw new Error("User id does not exist."); + } + + const queryResult: FriendshipInputDTO[] = await friendshipDatabase.findFriendship(authorId); + + const existFriendship = queryResult.findIndex((user) => { + return user.friend_id === friendId; + }); + + if (existFriendship === -1) { + throw new Error("friendship already exists!"); + } + + await friendshipDatabase.deletePost(input); + } catch (error: any) { + throw new Error(error.message); + } + }; +} diff --git a/src/business/LikeBusiness.ts b/src/business/LikeBusiness.ts new file mode 100644 index 0000000..f64f80c --- /dev/null +++ b/src/business/LikeBusiness.ts @@ -0,0 +1,107 @@ +import { LikeDatabase } from "../data/LikeDatabase"; +import { PostDatabase } from "../data/PostDatabase"; +import { UserDatabase } from "../data/UserDatabase"; +import { LikeInputDataDTO, LikeInputDTO, TLike } from "../model/likes"; +import { TPost } from "../model/Posts"; + +const likeDatabase = new LikeDatabase(); +const userDatabase = new UserDatabase(); +const postDatabase = new PostDatabase(); + +export class LikeBusiness { + createLike = async (input: TLike): Promise => { + try { + const { postId, authorId } = input; + + if (!postId || !authorId) { + throw new Error("Fill in the postId, authorId."); + } + + const queryUser = await userDatabase.findUser(); + const queryPost = await postDatabase.findPost(postId); + const existPost = queryPost.findIndex((post) => { + return post.id === postId; + }); + + if (existPost === -1) { + throw new Error("Post id does not exist."); + } + + const existauthorId = queryUser.findIndex((user) => { + return user.id === authorId; + }); + + if (existauthorId === -1) { + throw new Error("User id does not exist."); + } + + const queryResult: LikeInputDTO[] = await likeDatabase.findLike(input); + + const existLike = queryResult.findIndex((like) => { + return like.post_id === postId; + }); + + if (existLike !== -1) { + throw new Error("You already liked this post!"); + } + + + const id: string = Date.now().toString(); + + await likeDatabase.insertLike({ + id, + postId, + authorId, + }); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findLike = () => {}; + + deleteLike = async (input: LikeInputDataDTO): Promise => { + try { + const { postId, authorId } = input; + + if (!postId || !authorId) { + throw new Error("Fill in the postId, authorId"); + } + + const queryUser = await userDatabase.findUser(); + const queryPost = await postDatabase.findPost(postId); + + const existPost = queryPost.findIndex((post) => { + return post.id === postId; + }); + + if (existPost === -1) { + throw new Error("Post id does not exist."); + } + + const existauthorId = queryUser.findIndex((user) => { + return user.id === authorId; + }); + + if (existauthorId === -1) { + throw new Error("User id does not exist."); + } + + const queryResult: LikeInputDTO[] = await likeDatabase.findLike(input); + + const existLike = queryResult.findIndex((like) => { + return like.post_id === postId; + }); + + if (existLike === -1) { + throw new Error("You didn't like this post!"); + } + + const idLike:string = queryResult[0].id + + await likeDatabase.deleteLike(idLike); + } catch (error: any) { + throw new Error(error.message); + } + }; +} diff --git a/src/business/PostBusiness.ts b/src/business/PostBusiness.ts new file mode 100644 index 0000000..453fc4e --- /dev/null +++ b/src/business/PostBusiness.ts @@ -0,0 +1,155 @@ +import { FriendshipDatabase } from "../data/FriendshipDatabase"; +import { PostDatabase } from "../data/PostDatabase"; +import { UserDatabase } from "../data/UserDatabase"; +import { FriendshipInputDTO } from "../model/Friendship"; +import { FeedPostDBDTO, FeedPostDTO, InpultPostDTO, PostIdDTO, PostTypeDTO, TPost } from "../model/Posts"; +import { dateFormat, dateFormatBr } from "../service/formatDate"; + +const postDatabase = new PostDatabase(); +const userDatabase = new UserDatabase(); +const friendshipDatabase = new FriendshipDatabase(); + +export class PostBusiness { + createPost = async (input: InpultPostDTO): Promise => { + try { + const { photo, description, type, createdAt, authorId } = input; + + if (!photo || !description || !type || !createdAt || !authorId) { + throw new Error( + 'Preencha os campos photo, description, type, authorId' + ); + } + + + if(type.toUpperCase() !== "normal".toUpperCase() && type.toUpperCase() !== "event".toUpperCase()){ + throw new Error( + 'Preencha o campo type com normal ou event' + ); + } + + const formatDate:any= dateFormat(createdAt.toString()) + + const id: string = Date.now().toString(); + + await postDatabase.insertPost({ + id, + photo, + description, + type, + createdAt:formatDate, + authorId + }) + + } catch (error:any) { + throw new Error(error.message) + } + }; + + findPost = async(input:PostIdDTO):Promise=> { + try { + + const { id } = input; + + if(!id){ + throw new Error( + 'Pass the id params' + ); + } + + const result:TPost[] = await postDatabase.findPost(id) + if (!result[0]) { + throw new Error("Post not found"); + } + return result; + + } catch (error:any) { + throw new Error(error.message) + } + }; + + feedPost = async(input:PostIdDTO):Promise => { + try { + const {id} = input; + + const queryUser = await userDatabase.findUser(); + const existUser = queryUser.findIndex((user)=>{ + return user.id === id + }) + + if(existUser === -1){ + throw new Error("User id does not exist.") + } + + const queryFriends: FriendshipInputDTO[] = await friendshipDatabase.findFriendship(id); + const existFriendship = queryFriends.findIndex((user) => { + return user.author_id === id; + }); + + if (existFriendship === -1) { + throw new Error("friendship already exists!"); + } + + const friends:string[] = [] + + for (let i = 0; i < queryFriends.length; i++) { + friends.push(queryFriends[i].friend_id); + } + const posts: FeedPostDTO[] = []; + const result:FeedPostDBDTO[] = await postDatabase.feedPost(friends) + result.map((item:any)=>{ + item.created_at = dateFormatBr(item.created_at.toString()) + return result + }) + for (let i = 0; i < result.length; i++) { + posts.push({ + id: result[i].id, + photo: result[i].photo, + description: result[i].description, + type: result[i].type, + createdAt: result[i].created_at, + authorId: result[i].author_id} + ) + + } + + return posts + } catch (error:any) { + throw new Error(error.message) + } + }; + feedPostAll = async(input:PostTypeDTO) => { + try { + + const{type} = input; + + if(type.toUpperCase() !== "normal".toUpperCase() && type.toUpperCase() !== "event".toUpperCase()){ + throw new Error( + 'Preencha o campo type com normal ou event' + ); + } + const posts: FeedPostDTO[] = []; + const result:FeedPostDBDTO[] = await postDatabase.feedPostAll(input) + result.map((item:any)=>{ + item.created_at = dateFormatBr(item.created_at.toString()) + return result + }) + + for (let i = 0; i < result.length; i++) { + posts.push({ + id: result[i].id, + photo: result[i].photo, + description: result[i].description, + type: result[i].type, + createdAt: result[i].created_at, + authorId: result[i].author_id} + ) + + } + + return posts + } catch (error:any) { + throw new Error(error.message) + } + }; + deletePost = () => {}; +} \ No newline at end of file diff --git a/src/business/UserBusiness.ts b/src/business/UserBusiness.ts new file mode 100644 index 0000000..0d11f48 --- /dev/null +++ b/src/business/UserBusiness.ts @@ -0,0 +1,42 @@ +import { UserDatabase } from "../data/UserDatabase"; + +export class UserBusiness { + createUser = async (input: any): Promise => { + try { + const { name, email, password } = input; + + const userDatabase = new UserDatabase(); + + if (!name || !email || !password) { + throw new Error( + 'Preencha os campos "name", "email" e "password"' + ); + } + + if (password.length < 6) { + throw new Error("Senha muito curta"); + } + + const userBase = await userDatabase.findUser(); + const existUser = userBase.findIndex((user)=>user.email === email) + + if(existUser != -1) { + throw new Error("Usuário já cadastrado "); + } + const id: string = Date.now().toString(); + + + await userDatabase.insertUser({ + id, + name, + email, + password, + }); + } catch (error:any) { + throw new Error(error.message) + } + }; + + findUser = () => {}; + deleteUser = () => {}; +} \ No newline at end of file diff --git a/src/controller/FriendshipController.ts b/src/controller/FriendshipController.ts new file mode 100644 index 0000000..47323d6 --- /dev/null +++ b/src/controller/FriendshipController.ts @@ -0,0 +1,37 @@ +import { Request, Response } from "express"; +import { FriendshipBusiness } from "../business/FriendshipBusiness"; +import { FriendInputDTO } from "../model/friends"; +import { DeleteFriendshipInputDTO } from "../model/Friendship"; +const friendshipBusiness = new FriendshipBusiness(); +export class FriendshipController { + createFriendship = async (req: Request, res: Response): Promise => { + try { + const input: FriendInputDTO = { + friendId: req.body.friendId, + authorId: req.body.authorId + }; + + await friendshipBusiness.createFriendship(input) + + res.status(201).send({ message: "Friendship created!" }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + findFriendship = () => {}; + + deleteFriendship = async(req:Request, res:Response):Promise => { + try { + const input: DeleteFriendshipInputDTO = { + friendId: req.body.friendId, + authorId: req.params.id + }; + + await friendshipBusiness.deleteFriendship(input) + res.status(201).send({ message: "deleted from friendship!" }); + } catch (error:any) { + res.status(400).send(error.message); + } + }; +} \ No newline at end of file diff --git a/src/controller/LikeController.ts b/src/controller/LikeController.ts new file mode 100644 index 0000000..67e0159 --- /dev/null +++ b/src/controller/LikeController.ts @@ -0,0 +1,36 @@ +import { Request, Response } from "express"; +import { LikeBusiness } from "../business/LikeBusiness"; + +const likeBusiness = new LikeBusiness(); +export class LikeController { + createLike = async (req: Request, res: Response): Promise => { + try { + const input: any = { + postId: req.body.postId, + authorId: req.body.authorId + }; + + await likeBusiness.createLike(input) + + res.status(201).send({ message: "Like success!" }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + findLike = () => {}; + + deleteLike = async(req:Request, res:Response):Promise => { + try { + const input: any = { + postId: req.body.postId, + authorId: req.params.id + }; + + await likeBusiness.deleteLike(input) + res.status(201).send({ message: "deleted from Like!" }); + } catch (error:any) { + res.status(400).send(error.message); + } + }; +} \ No newline at end of file diff --git a/src/controller/PostController.ts b/src/controller/PostController.ts new file mode 100644 index 0000000..622f133 --- /dev/null +++ b/src/controller/PostController.ts @@ -0,0 +1,69 @@ +import { Request, Response } from "express"; +import { PostBusiness } from "../business/PostBusiness"; +import { InpultPostDTO, PostIdDTO, PostTypeDTO } from "../model/Posts"; + +const postBusiness = new PostBusiness() + +export class PostController { + createPost = async (req: Request, res: Response): Promise => { + try { + const input: InpultPostDTO = { + photo: req.body.photo, + description:req.body.description, + type: req.body.type, + createdAt: req.body.createdAt, + authorId: req.body.authorId + }; + + await postBusiness.createPost(input) + + res.status(201).send({ message: "Post criado!" }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + findPost = async (req: Request, res: Response): Promise => { + try { + const input: PostIdDTO = { + id: req.params.id + }; + + const posts = await postBusiness.findPost(input) + + res.status(200).send({ posts }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + feedPost = async(req: Request, res: Response) => { + try { + const input: PostIdDTO = { + id: req.params.id + }; + + const posts = await postBusiness.feedPost(input) + + res.status(200).send({ posts }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + feedPostAll = async(req: Request, res: Response) => { + try { + const input: PostTypeDTO = { + type: req.body.type + }; + + const posts = await postBusiness.feedPostAll(input) + + res.status(200).send({ posts }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + deletePost = () => {}; + +} \ No newline at end of file diff --git a/src/controller/UserController.ts b/src/controller/UserController.ts new file mode 100644 index 0000000..672025b --- /dev/null +++ b/src/controller/UserController.ts @@ -0,0 +1,24 @@ +import { Request, Response } from "express"; +import { UserBusiness } from "../business/UserBusiness"; + +export class UserController { + createUser = async (req: Request, res: Response): Promise => { + try { + const input: any = { + name: req.body.name, + email: req.body.email, + password: req.body.password, + }; + + const userBusiness = new UserBusiness() + await userBusiness.createUser(input) + + res.status(201).send({ message: "Usuário criado!" }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + findUser = () => {}; + deleteUser = () => {}; +} \ No newline at end of file diff --git a/src/data/BaseDatabase.ts b/src/data/BaseDatabase.ts new file mode 100644 index 0000000..2663d9c --- /dev/null +++ b/src/data/BaseDatabase.ts @@ -0,0 +1,17 @@ +import knex from "knex" +import dotenv from "dotenv"; + +dotenv.config(); +export abstract class BaseDatabase { + protected static connection = knex({ + client: "mysql", + connection: { + host: process.env.DB_HOST, + port: 3306, + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_DATABASE, + multipleStatements: true + }, +}); +} \ No newline at end of file diff --git a/src/data/FriendshipDatabase.ts b/src/data/FriendshipDatabase.ts new file mode 100644 index 0000000..e37f5c6 --- /dev/null +++ b/src/data/FriendshipDatabase.ts @@ -0,0 +1,67 @@ +import { BaseDatabase } from "./BaseDatabase"; +import { + DeleteFriendshipInputDTO, + FriendshipInputDataDTO, + FriendshipInputDTO + } from "../model/Friendship"; + +export class FriendshipDatabase extends BaseDatabase { + private static TABLE_NAME = "labook_friendship"; + insertPost = async (friend: FriendshipInputDataDTO): Promise => { + try { + await FriendshipDatabase.connection + .insert({ + id: friend.id, + friend_id: friend.friendId, + author_id: friend.authorId, + }) + .into(FriendshipDatabase.TABLE_NAME); + + await FriendshipDatabase.connection + .insert({ + id: friend.idRows, + friend_id: friend.authorId, + author_id: friend.friendId, + }) + .into(FriendshipDatabase.TABLE_NAME); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findFriendship = async (userid: string): Promise => { + try { + const friends: FriendshipInputDTO[] = []; + + const result = await FriendshipDatabase.connection + .select("*") + .from(FriendshipDatabase.TABLE_NAME) + .where({ author_id: userid }); + + for (let friend of result) { + friends.push(friend); + } + + return friends; + } catch (error: any) { + throw new Error(error.message); + } + }; + deletePost = async (input: DeleteFriendshipInputDTO): Promise => { + try { + const { friendId, authorId } = input; + + await FriendshipDatabase.connection + .from(FriendshipDatabase.TABLE_NAME) + .where({ author_id: authorId, friend_id: friendId }) + .delete(); + + await FriendshipDatabase.connection + .from(FriendshipDatabase.TABLE_NAME) + .where({ author_id: friendId, friend_id: authorId }) + .delete(); + } catch (error: any) { + throw new Error(error.message); + } + }; +} diff --git a/src/data/LikeDatabase.ts b/src/data/LikeDatabase.ts new file mode 100644 index 0000000..a436826 --- /dev/null +++ b/src/data/LikeDatabase.ts @@ -0,0 +1,47 @@ +import { BaseDatabase } from "./BaseDatabase"; +import { TPost } from "../model/Posts"; +import { LikeInputDataDTO, LikeInputDTO, TLike } from "../model/likes"; + +export class LikeDatabase extends BaseDatabase { + private static TABLE_NAME = "labook_likes"; + insertLike = async (input: LikeInputDataDTO): Promise => { + try { + await LikeDatabase.connection + .insert({ + id: input.id, + post_id: input.postId, + author_id: input.authorId, + }) + .into(LikeDatabase.TABLE_NAME); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findLike = async (input: LikeInputDataDTO): Promise => { + try { + + const {postId,authorId}= input; + + const result = await LikeDatabase.connection + .select("*") + .from(LikeDatabase.TABLE_NAME) + .where({ post_id: postId, author_id: authorId }); + + return result; + } catch (error: any) { + throw new Error(error.message); + } + }; + + deleteLike = async (input: string): Promise => { + try { + await LikeDatabase.connection + .from(LikeDatabase.TABLE_NAME) + .where({ id: input }) + .delete(); + } catch (error: any) { + throw new Error(error.message); + } + }; +} diff --git a/src/data/PostDatabase.ts b/src/data/PostDatabase.ts new file mode 100644 index 0000000..8d45f34 --- /dev/null +++ b/src/data/PostDatabase.ts @@ -0,0 +1,69 @@ +import { BaseDatabase } from "./BaseDatabase"; +import { FeedPostDBDTO, PostTypeDTO, TPost } from "../model/Posts"; + +export class PostDatabase extends BaseDatabase { + private static TABLE_NAME = "labook_posts"; + insertPost = async (post: TPost): Promise => { + try { + await PostDatabase.connection + .insert({ + id: post.id, + photo: post.photo, + description: post.description, + type: post.type, + created_at: post.createdAt, + author_id: post.authorId, + }) + .into(PostDatabase.TABLE_NAME); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findPost = async (postid: string): Promise => { + try { + const posts: TPost[] = []; + + const result = await PostDatabase.connection + .select("*") + .from(PostDatabase.TABLE_NAME) + .where({ id: postid }); + + posts.push({ + id: result[0].id, + photo: result[0].photo, + description: result[0].description, + type: result[0].type, + createdAt: result[0].created_at, + authorId: result[0].author_id, + }); + + return posts; + } catch (error: any) { + throw new Error(error.message); + } + }; + + feedPost = async (input: string[]): Promise => { + try { + const [result] = await PostDatabase.connection.raw( + `select * from ${PostDatabase.TABLE_NAME} where author_id in (${input}) order by created_at;` + ); + return result; + } catch (error: any) { + throw new Error(error.message); + } + }; + + feedPostAll = async (input: PostTypeDTO): Promise => { + try { + const [result] = await PostDatabase.connection.raw( + `select * from ${PostDatabase.TABLE_NAME} where type = "${input.type}" order by created_at;` + ); + return result; + } catch (error: any) { + throw new Error(error.message); + } + }; + deletePost = () => {}; +} diff --git a/src/data/UserDatabase.ts b/src/data/UserDatabase.ts new file mode 100644 index 0000000..73e5b02 --- /dev/null +++ b/src/data/UserDatabase.ts @@ -0,0 +1,41 @@ +import { BaseDatabase } from "./BaseDatabase"; +import { TUser } from "../model/User"; + +export class UserDatabase extends BaseDatabase { + private static TABLE_NAME = "labook_users"; + insertUser = async (user: TUser): Promise => { + try { + await UserDatabase.connection + .insert({ + id: user.id, + name: user.name, + email: user.email, + password: user.password, + }) + .into(UserDatabase.TABLE_NAME); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findUser = async (): Promise => { + try { + const users: TUser[] = []; + + const result = await UserDatabase.connection + .select("*") + .from(UserDatabase.TABLE_NAME); + + + for (let user of result) { + users.push(user); + } + + return users; + + } catch (error: any) { + throw new Error(error.message); + } + }; + deleteUser = () => {}; +} diff --git a/src/dataBase/connection.ts b/src/data/connection.ts similarity index 87% rename from src/dataBase/connection.ts rename to src/data/connection.ts index db29f16..badde9c 100644 --- a/src/dataBase/connection.ts +++ b/src/data/connection.ts @@ -1,7 +1,7 @@ import knex from "knex" -import dotenv from "dotenv"; +import dotenv from "dotenv" -dotenv.config(); +dotenv.config() const connection = knex({ client: "mysql", diff --git a/src/dataBase/migrations.ts b/src/data/migrations.ts similarity index 96% rename from src/dataBase/migrations.ts rename to src/data/migrations.ts index d3bf210..1dfeb40 100644 --- a/src/dataBase/migrations.ts +++ b/src/data/migrations.ts @@ -21,7 +21,7 @@ const createTables = async () => { CREATE TABLE IF NOT EXISTS labook_friendship( id VARCHAR(255) PRIMARY KEY, friend_id VARCHAR(255) NOT NULL, - author_id VARCHAR(255), + author_id VARCHAR(255) NOT NULL, FOREIGN KEY (author_id) REFERENCES labook_users (id), FOREIGN KEY (friend_id) REFERENCES labook_users (id) ) diff --git a/src/endpoints/createFriendship.ts b/src/endpoints/createFriendship.ts deleted file mode 100644 index 487fad9..0000000 --- a/src/endpoints/createFriendship.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Request, Response } from "express"; -import connection from "../dataBase/connection"; -export const createFriendship = async (req: Request, res: Response) => { - try { - let message = "Success!" - - const { friend, authorId } = req.body - console.log(); - - - const friendship: string = Date.now().toString() - - await connection("labook_friendship") - .insert({ - id:friendship, - friend_id: friend, - author_id: authorId - }) - - res.status(201).send({ message }) - - } catch (error:any) { - let message = error.sqlMessage || error.message - res.statusCode = 400 - res.send({ message }) - } - } \ No newline at end of file diff --git a/src/endpoints/createPost.ts b/src/endpoints/createPost.ts deleted file mode 100644 index 0174e31..0000000 --- a/src/endpoints/createPost.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Request, Response } from "express"; -import connection from "../dataBase/connection"; -export const createPost = async (req: Request, res: Response) => { - try { - let message = "Success!" - - const { photo, description, type, authorId } = req.body - console.log(); - - - const postId: string = Date.now().toString() - - await connection("labook_posts") - .insert({ - id:postId, - photo, - description, - type, - author_id: authorId - }) - - res.status(201).send({ message }) - - } catch (error:any) { - let message = error.sqlMessage || error.message - res.statusCode = 400 - res.send({ message }) - } - } \ No newline at end of file diff --git a/src/endpoints/createUser.ts b/src/endpoints/createUser.ts deleted file mode 100644 index 87c4308..0000000 --- a/src/endpoints/createUser.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Request, Response } from "express"; -import connection from "../dataBase/connection"; -export const createUser =async (req: Request, res: Response) => { - let errorCode = 400; - try{ - let message = "Success!" - const { name, email, password } = req.body - - if (!name || !email || !password) { - res.statusCode = 406 - message = '"name", "email" and "password" must be provided' - throw new Error(message) - } - - const id: string = Date.now().toString() - - await connection('labook_users') - .insert({ - id, - name, - email, - password - }) - - res.status(201).send({ message }) - - } catch (error:any) { - res.statusCode = 400 - let message = error.sqlMessage || error.message - res.send({ message }) - } - -} \ No newline at end of file diff --git a/src/endpoints/deleteFriendship.ts b/src/endpoints/deleteFriendship.ts deleted file mode 100644 index 1ea2351..0000000 --- a/src/endpoints/deleteFriendship.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Request, Response } from "express"; -import connection from "../dataBase/connection"; -import { TFriendship } from "../models/Friendship"; -export const deleteFriendships = async (req: Request, res: Response) => { - try { - let message = "Success!" - - const { id } = req.params - const {friend} = req.body - - const queryResult: TFriendship[] = await connection("labook_friendship") - .select("*") - .where({ author_id: id, friend_id: friend }) - - - if (!queryResult[0]) { - res.statusCode = 404 - message = "friend not found" - throw new Error(message) - } - - const queryDelete: any = await connection("labook_friendship") - .where({ author_id: id, friend_id: friend }) - .del() - - res.status(200).send({ message }) - - } catch (error:any) { - let message = error.sqlMessage || error.message - res.statusCode = 400 - res.send({ message }) - } - } \ No newline at end of file diff --git a/src/endpoints/getFriendships.ts b/src/endpoints/getFriendships.ts deleted file mode 100644 index 2417db2..0000000 --- a/src/endpoints/getFriendships.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { Request, Response } from "express"; -import connection from "../dataBase/connection"; -import { TFriends } from "../models/friends"; -import { TFriendship } from "../models/Friendship"; -import { TUser } from "../models/User"; -export const getFriendships = async (req: Request, res: Response) => { - try { - let message = "Success!"; - - const { id } = req.params; - - if (!id) { - res.statusCode = 404; - message = "id obrigation"; - throw new Error(message); - } - - const queryResult: TFriendship[] = await connection("labook_friendship") - .select("*") - .where({ author_id: id }); - - if (!queryResult[0]) { - res.statusCode = 404; - message = "friendship not found"; - throw new Error(message); - } - - let friends:TFriends[] = []; - for (let i = 0; i < queryResult.length; i++) { - const queryUser:TUser[] = await connection("labook_users") - .select("*") - .where({ id: queryResult[i].friend_id }); - - if (!queryUser[0]) { - res.statusCode = 404; - message = "friendship not found"; - throw new Error(message); - } else { - friends.push({ - friend_id: queryUser[0].id, - name: queryUser[0].name, - }); - } - } - - res.status(200).send({ message, friends }); - } catch (error: any) { - let message = error.sqlMessage || error.message; - res.statusCode = 400; - res.send({ message }); - } -}; diff --git a/src/endpoints/getPosts.ts b/src/endpoints/getPosts.ts deleted file mode 100644 index 0105693..0000000 --- a/src/endpoints/getPosts.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Request, Response } from "express"; -import connection from "../dataBase/connection"; -import { TPost } from "../models/Posts"; -export const getPost = async (req: Request, res: Response) => { - try { - let message = "Success!" - - const { id } = req.params - - const queryResult: any = await connection("labook_posts") - .select("*") - .where({ author_id: id }) - - - if (!queryResult[0]) { - res.statusCode = 404 - message = "Post not found" - throw new Error(message) - } - - const post: TPost = { - id: queryResult[0].id, - photo: queryResult[0].photo, - description: queryResult[0].description, - type: queryResult[0].type, - createdAt: queryResult[0].created_at, - authorId: queryResult[0].author_id, - } - - res.status(200).send({ message, post }) - - } catch (error:any) { - let message = error.sqlMessage || error.message - res.statusCode = 400 - res.send({ message }) - } - } \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 7e730a6..8b801b4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,9 @@ -import express, { Express, Request, Response } from "express" +import express, { Express } from "express" import cors from "cors" -import { createUser } from "./endpoints/createUser" -import { createPost } from "./endpoints/createPost" -import { getPost } from "./endpoints/getPosts" -import { createFriendship } from "./endpoints/createFriendship" -import { getFriendships } from "./endpoints/getFriendships" -import { deleteFriendships } from "./endpoints/deleteFriendship" +import { UserController } from "./controller/UserController" +import { PostController } from "./controller/PostController" +import { FriendshipController } from "./controller/FriendshipController" +import { LikeController } from "./controller/LikeController" /**************************** CONFIG ******************************/ @@ -19,15 +17,26 @@ app.listen(3003, () => { /**************************** ENDPOINTS ******************************/ -app.post('/users',createUser); +const userController = new UserController(); +const postController = new PostController(); +const friendshipController = new FriendshipController(); +const likeController = new LikeController(); -app.post('/post',createPost); +app.post('/users',userController.createUser); -app.post('/friendship',createFriendship); +app.post('/post',postController.createPost); -app.delete('/friendship/:id',deleteFriendships); +app.post('/friendship',friendshipController.createFriendship); -app.get('/posts/:id',getPost); +app.post('/like',likeController.createLike); -app.get('/friendship/:id',getFriendships); +app.delete('/friendship/:id',friendshipController.deleteFriendship); + +app.delete('/like/:id',likeController.deleteLike); + +app.get('/posts/:id',postController.findPost); + +app.get('/feeds/:id',postController.feedPost); + +app.get('/feeds',postController.feedPostAll); diff --git a/src/model/Friendship.ts b/src/model/Friendship.ts new file mode 100644 index 0000000..c97dda7 --- /dev/null +++ b/src/model/Friendship.ts @@ -0,0 +1,24 @@ +export type TFriendship = { + id: string, + friendId: string, + authorId: string + +} +export interface FriendshipInputDTO{ + id: string, + friend_id: string, + author_id: string + +} +export interface FriendshipInputDataDTO{ + id: string, + idRows: string, + friendId: string, + authorId: string + +} +export interface DeleteFriendshipInputDTO{ + friendId: string, + authorId: string + +} \ No newline at end of file diff --git a/src/model/Posts.ts b/src/model/Posts.ts new file mode 100644 index 0000000..85947ee --- /dev/null +++ b/src/model/Posts.ts @@ -0,0 +1,45 @@ +enum TPOST_TYPES { + NORMAL = "normal", + EVENT = "event" + } + + export type TPost = { + id: string, + photo: string, + description: string, + type: TPOST_TYPES, + createdAt: Date, + authorId: string + } + + export interface FeedPostDTO{ + id: string, + photo: string, + description: string, + type: TPOST_TYPES, + createdAt: Date, + authorId: string + } + export interface FeedPostDBDTO{ + id: string, + photo: string, + description: string, + type: TPOST_TYPES, + created_at: Date, + author_id: string + } + export interface InpultPostDTO{ + photo: string, + description: string, + type: TPOST_TYPES, + createdAt: Date, + authorId: string + } + + export interface PostIdDTO{ + id: string, + } + + export interface PostTypeDTO{ + type: TPOST_TYPES + } \ No newline at end of file diff --git a/src/models/User.ts b/src/model/User.ts similarity index 100% rename from src/models/User.ts rename to src/model/User.ts diff --git a/src/model/friends.ts b/src/model/friends.ts new file mode 100644 index 0000000..2009adc --- /dev/null +++ b/src/model/friends.ts @@ -0,0 +1,10 @@ +export type TFriends = { + friend_id: string, + name: string + +} + +export interface FriendInputDTO{ + friendId: string, + authorId: string +} \ No newline at end of file diff --git a/src/model/likes.ts b/src/model/likes.ts new file mode 100644 index 0000000..fd6558b --- /dev/null +++ b/src/model/likes.ts @@ -0,0 +1,21 @@ +export type TLike= { + id: string, + postId: string, + authorId: string + +} +export interface LikeInputDTO{ + id: string, + post_id: string, + author_id: string + +} +export interface LikeInputDataDTO{ + id: string, + postId: string, + authorId: string + +} +export interface DeleteLikeInputDTO{ + id: string, +} \ No newline at end of file diff --git a/src/models/Friendship.ts b/src/models/Friendship.ts deleted file mode 100644 index d0a7120..0000000 --- a/src/models/Friendship.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type TFriendship = { - id: string, - friend_id: string, - author: string - -} \ No newline at end of file diff --git a/src/models/Posts.ts b/src/models/Posts.ts deleted file mode 100644 index e79fe19..0000000 --- a/src/models/Posts.ts +++ /dev/null @@ -1,13 +0,0 @@ -enum TPOST_TYPES { - NORMAL = "normal", - EVENT = "event" - } - - export type TPost = { - id: string, - photo: string, - description: string, - type: TPOST_TYPES, - createdAt: Date, - authorId: string - } \ No newline at end of file diff --git a/src/models/friends.ts b/src/models/friends.ts deleted file mode 100644 index 00e114e..0000000 --- a/src/models/friends.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type TFriends = { - friend_id: string, - name: string - -} \ No newline at end of file diff --git a/src/service/formatDate.ts b/src/service/formatDate.ts new file mode 100644 index 0000000..02677c1 --- /dev/null +++ b/src/service/formatDate.ts @@ -0,0 +1,13 @@ +export const dateFormat = (dateAccount: string): string => { + let parts = dateAccount.split("/"); + dateAccount = `${parts[2]}-${parts[1]}-${parts[0]}`; + return dateAccount; +}; +export const dateFormatBr = (dateAccount: string): string => { + let data = new Date(dateAccount); + let date = String(data.getDate()).padStart(2, "0"); + let month = String(data.getMonth() + 1).padStart(2, "0"); + let fullYear = data.getFullYear(); + let dataAtual = date + "/" + month + "/" + fullYear; + return dataAtual; +}; From d28574cdc71368b0240dfcdd751db09514629e50 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Thu, 2 Feb 2023 20:29:25 -0300 Subject: [PATCH 06/22] =?UTF-8?q?Fix:=20se=20aplicado,=20este=20commit=20c?= =?UTF-8?q?orrigir=C3=A1=20o=20erro=20de=20valida=C3=A7=C3=A3o=20do=20post?= =?UTF-8?q?=20existe=20no=20DB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- request.rest | 4 ++-- src/business/FriendshipBusiness.ts | 2 +- src/business/PostBusiness.ts | 9 +++++++++ src/data/PostDatabase.ts | 16 +++------------- 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/request.rest b/request.rest index 4ae4ee5..fe407af 100644 --- a/request.rest +++ b/request.rest @@ -22,7 +22,7 @@ Content-Type: application/json "description": "foto da viagem", "type": "event", "createdAt": "02/01/2023", - "authorId": "1675081697628" + "authorId": "1675081679184" } ### Create a new Friendship @@ -51,7 +51,7 @@ GET http://localhost:3003/feeds Content-Type: application/json { - "type":"event" + "type":"normal" } ### Like Post diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index 4699e03..e9b5e99 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -95,7 +95,7 @@ export class FriendshipBusiness { }); if (existFriendship === -1) { - throw new Error("friendship already exists!"); + throw new Error("friendship does not exist!"); } await friendshipDatabase.deletePost(input); diff --git a/src/business/PostBusiness.ts b/src/business/PostBusiness.ts index 453fc4e..8585706 100644 --- a/src/business/PostBusiness.ts +++ b/src/business/PostBusiness.ts @@ -26,6 +26,15 @@ export class PostBusiness { 'Preencha o campo type com normal ou event' ); } + + const queryUser = await userDatabase.findUser(); + const existUser = queryUser.findIndex((user)=>{ + return user.id === authorId + }) + + if(existUser === -1){ + throw new Error("User id does not exist.") + } const formatDate:any= dateFormat(createdAt.toString()) diff --git a/src/data/PostDatabase.ts b/src/data/PostDatabase.ts index 8d45f34..6a1166e 100644 --- a/src/data/PostDatabase.ts +++ b/src/data/PostDatabase.ts @@ -22,23 +22,13 @@ export class PostDatabase extends BaseDatabase { findPost = async (postid: string): Promise => { try { - const posts: TPost[] = []; - + const result = await PostDatabase.connection .select("*") .from(PostDatabase.TABLE_NAME) .where({ id: postid }); - - posts.push({ - id: result[0].id, - photo: result[0].photo, - description: result[0].description, - type: result[0].type, - createdAt: result[0].created_at, - authorId: result[0].author_id, - }); - - return posts; + + return result; } catch (error: any) { throw new Error(error.message); } From a50b97334b01d2eaaa9d90823fd4f3093388e938 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Fri, 3 Feb 2023 13:32:23 -0300 Subject: [PATCH 07/22] Feat: se aplicado, este commit add o endPoint comment --- request.rest | 10 ++++++ src/business/CommentsBusiness.ts | 50 ++++++++++++++++++++++++++++ src/business/FriendshipBusiness.ts | 3 +- src/business/LikeBusiness.ts | 7 ++-- src/business/UserBusiness.ts | 3 +- src/controller/CommentsController.ts | 25 ++++++++++++++ src/controller/LikeController.ts | 5 +-- src/controller/UserController.ts | 3 +- src/data/CommentsDatabase.ts | 42 +++++++++++++++++++++++ src/data/LikeDatabase.ts | 5 ++- src/data/UserDatabase.ts | 8 ++--- src/index.ts | 4 +++ src/model/Comments.ts | 22 ++++++++++++ src/model/User.ts | 7 +++- src/model/likes.ts | 11 +++--- 15 files changed, 180 insertions(+), 25 deletions(-) create mode 100644 src/business/CommentsBusiness.ts create mode 100644 src/controller/CommentsController.ts create mode 100644 src/data/CommentsDatabase.ts create mode 100644 src/model/Comments.ts diff --git a/request.rest b/request.rest index fe407af..7333f64 100644 --- a/request.rest +++ b/request.rest @@ -69,4 +69,14 @@ Content-Type: application/json { "postId":"1675089703154" +} + +### Comment Post +POST http://localhost:3003/comments +Content-Type: application/json + +{ + "comment":"Linda foto", + "postId":"1675379034720", + "authorId": "1675001631299" } \ No newline at end of file diff --git a/src/business/CommentsBusiness.ts b/src/business/CommentsBusiness.ts new file mode 100644 index 0000000..0c56103 --- /dev/null +++ b/src/business/CommentsBusiness.ts @@ -0,0 +1,50 @@ +import { CommentDatabase } from "../data/CommentsDatabase"; +import { PostDatabase } from "../data/PostDatabase"; +import { UserDatabase } from "../data/UserDatabase"; +import { InputCommentControllerDTO } from "../model/Comments"; +const commentDatabase = new CommentDatabase(); +const userDatabase = new UserDatabase(); +const postDatabase = new PostDatabase(); + +export class CommentsBusiness { + createComment = async (input: InputCommentControllerDTO): Promise => { + try { + const { comment, postId, authorId } = input; + + + if (!comment || !postId || !authorId) { + throw new Error( + 'Preencha os campos "comment", "postId" e "authorId"' + ); + } + + const userBase = await userDatabase.findUser(); + const existUser = userBase.findIndex((user)=>user.id === authorId); + + if(existUser === -1) { + throw new Error("User not exist."); + } + const postBase = await postDatabase.findPost(postId); + const existPost = postBase.findIndex((post)=>post.id === postId); + + if(existPost === -1) { + throw new Error("Post not exist."); + } + + const id: string = Date.now().toString(); + + + await commentDatabase.insertcomment({ + id, + comment, + postId, + authorId, + }); + } catch (error:any) { + throw new Error(error.message) + } + }; + + findComment = () => {}; + deleteComment = () => {}; +} \ No newline at end of file diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index e9b5e99..dc97fc9 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -3,8 +3,7 @@ import { UserDatabase } from "../data/UserDatabase"; import { FriendInputDTO } from "../model/friends"; import { DeleteFriendshipInputDTO, - FriendshipInputDTO, - TFriendship, + FriendshipInputDTO } from "../model/Friendship"; const friendshipDatabase = new FriendshipDatabase(); diff --git a/src/business/LikeBusiness.ts b/src/business/LikeBusiness.ts index f64f80c..db146fd 100644 --- a/src/business/LikeBusiness.ts +++ b/src/business/LikeBusiness.ts @@ -1,15 +1,14 @@ import { LikeDatabase } from "../data/LikeDatabase"; import { PostDatabase } from "../data/PostDatabase"; import { UserDatabase } from "../data/UserDatabase"; -import { LikeInputDataDTO, LikeInputDTO, TLike } from "../model/likes"; -import { TPost } from "../model/Posts"; +import { LikeInputControllerDTO, LikeInputDataDTO, LikeInputDTO } from "../model/likes"; const likeDatabase = new LikeDatabase(); const userDatabase = new UserDatabase(); const postDatabase = new PostDatabase(); export class LikeBusiness { - createLike = async (input: TLike): Promise => { + createLike = async (input: LikeInputControllerDTO): Promise => { try { const { postId, authorId } = input; @@ -60,7 +59,7 @@ export class LikeBusiness { findLike = () => {}; - deleteLike = async (input: LikeInputDataDTO): Promise => { + deleteLike = async (input: LikeInputControllerDTO): Promise => { try { const { postId, authorId } = input; diff --git a/src/business/UserBusiness.ts b/src/business/UserBusiness.ts index 0d11f48..ffb8932 100644 --- a/src/business/UserBusiness.ts +++ b/src/business/UserBusiness.ts @@ -1,7 +1,8 @@ import { UserDatabase } from "../data/UserDatabase"; +import { InputControllerDTO } from "../model/User"; export class UserBusiness { - createUser = async (input: any): Promise => { + createUser = async (input: InputControllerDTO): Promise => { try { const { name, email, password } = input; diff --git a/src/controller/CommentsController.ts b/src/controller/CommentsController.ts new file mode 100644 index 0000000..0a77d9c --- /dev/null +++ b/src/controller/CommentsController.ts @@ -0,0 +1,25 @@ +import { Request, Response } from "express"; +import { CommentsBusiness} from "../business/CommentsBusiness"; +import { InputCommentControllerDTO } from "../model/Comments"; + +export class CommentController { + createComment = async (req: Request, res: Response): Promise => { + try { + const input: InputCommentControllerDTO = { + comment: req.body.comment, + postId: req.body.postId, + authorId: req.body.authorId + }; + + const commentBusiness = new CommentsBusiness() + await commentBusiness.createComment(input) + + res.status(201).send({ message: "Comment create!" }); + } catch (error: any) { + res.status(400).send(error.message); + } + }; + + findComment = () => {}; + deleteComment = () => {}; +} \ No newline at end of file diff --git a/src/controller/LikeController.ts b/src/controller/LikeController.ts index 67e0159..2f43681 100644 --- a/src/controller/LikeController.ts +++ b/src/controller/LikeController.ts @@ -1,11 +1,12 @@ import { Request, Response } from "express"; import { LikeBusiness } from "../business/LikeBusiness"; +import { LikeInputControllerDTO } from "../model/likes"; const likeBusiness = new LikeBusiness(); export class LikeController { createLike = async (req: Request, res: Response): Promise => { try { - const input: any = { + const input: LikeInputControllerDTO = { postId: req.body.postId, authorId: req.body.authorId }; @@ -22,7 +23,7 @@ export class LikeController { deleteLike = async(req:Request, res:Response):Promise => { try { - const input: any = { + const input: LikeInputControllerDTO = { postId: req.body.postId, authorId: req.params.id }; diff --git a/src/controller/UserController.ts b/src/controller/UserController.ts index 672025b..0421655 100644 --- a/src/controller/UserController.ts +++ b/src/controller/UserController.ts @@ -1,10 +1,11 @@ import { Request, Response } from "express"; import { UserBusiness } from "../business/UserBusiness"; +import { InputControllerDTO } from "../model/User"; export class UserController { createUser = async (req: Request, res: Response): Promise => { try { - const input: any = { + const input: InputControllerDTO = { name: req.body.name, email: req.body.email, password: req.body.password, diff --git a/src/data/CommentsDatabase.ts b/src/data/CommentsDatabase.ts new file mode 100644 index 0000000..056eb40 --- /dev/null +++ b/src/data/CommentsDatabase.ts @@ -0,0 +1,42 @@ +import { BaseDatabase } from "./BaseDatabase"; +import { CommentInputBDTO, InputCommentDTO } from "../model/Comments"; + +export class CommentDatabase extends BaseDatabase { + private static TABLE_NAME ="labook_comments"; + insertcomment = async (comment: InputCommentDTO): Promise => { + try { + await CommentDatabase.connection + .insert({ + id: comment.id, + comment: comment.comment, + post_id: comment.postId, + author_id: comment.authorId + }) + .into(CommentDatabase.TABLE_NAME); + } catch (error: any) { + throw new Error(error.message); + } + }; + + findcomment = async (input:string): Promise => { + try { + const comments: CommentInputBDTO[] = []; + + const result = await CommentDatabase.connection + .select("*") + .from(CommentDatabase.TABLE_NAME) + .where({input}); + + + for (let comment of result) { + comments.push(comment); + } + + return comments; + + } catch (error: any) { + throw new Error(error.message); + } + }; + deletecomment = () => {}; +} diff --git a/src/data/LikeDatabase.ts b/src/data/LikeDatabase.ts index a436826..e2ee473 100644 --- a/src/data/LikeDatabase.ts +++ b/src/data/LikeDatabase.ts @@ -1,6 +1,5 @@ import { BaseDatabase } from "./BaseDatabase"; -import { TPost } from "../model/Posts"; -import { LikeInputDataDTO, LikeInputDTO, TLike } from "../model/likes"; +import { LikeInputControllerDTO, LikeInputDataDTO, LikeInputDTO } from "../model/likes"; export class LikeDatabase extends BaseDatabase { private static TABLE_NAME = "labook_likes"; @@ -18,7 +17,7 @@ export class LikeDatabase extends BaseDatabase { } }; - findLike = async (input: LikeInputDataDTO): Promise => { + findLike = async (input: LikeInputControllerDTO): Promise => { try { const {postId,authorId}= input; diff --git a/src/data/UserDatabase.ts b/src/data/UserDatabase.ts index 73e5b02..0630728 100644 --- a/src/data/UserDatabase.ts +++ b/src/data/UserDatabase.ts @@ -1,9 +1,9 @@ import { BaseDatabase } from "./BaseDatabase"; -import { TUser } from "../model/User"; +import { UserDTO } from "../model/User"; export class UserDatabase extends BaseDatabase { private static TABLE_NAME = "labook_users"; - insertUser = async (user: TUser): Promise => { + insertUser = async (user: UserDTO): Promise => { try { await UserDatabase.connection .insert({ @@ -18,9 +18,9 @@ export class UserDatabase extends BaseDatabase { } }; - findUser = async (): Promise => { + findUser = async (): Promise => { try { - const users: TUser[] = []; + const users: UserDTO[] = []; const result = await UserDatabase.connection .select("*") diff --git a/src/index.ts b/src/index.ts index 8b801b4..668c5d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,7 @@ import { UserController } from "./controller/UserController" import { PostController } from "./controller/PostController" import { FriendshipController } from "./controller/FriendshipController" import { LikeController } from "./controller/LikeController" +import { CommentController } from "./controller/CommentsController" /**************************** CONFIG ******************************/ @@ -21,6 +22,7 @@ const userController = new UserController(); const postController = new PostController(); const friendshipController = new FriendshipController(); const likeController = new LikeController(); +const commentController = new CommentController(); app.post('/users',userController.createUser); @@ -30,6 +32,8 @@ app.post('/friendship',friendshipController.createFriendship); app.post('/like',likeController.createLike); +app.post('/comments', commentController.createComment); + app.delete('/friendship/:id',friendshipController.deleteFriendship); app.delete('/like/:id',likeController.deleteLike); diff --git a/src/model/Comments.ts b/src/model/Comments.ts new file mode 100644 index 0000000..a9ea19e --- /dev/null +++ b/src/model/Comments.ts @@ -0,0 +1,22 @@ +export interface InputCommentDTO{ + id: string, + comment: string, + postId: string, + authorId: string + } + export interface CommentInputBDTO{ + id: string, + comment: string, + created_at: Date, + post_id: string, + author_id: string + } + export interface InputCommentControllerDTO{ + comment: string, + postId: string, + authorId: string + } + + export interface CommentIdDTO{ + id: string, + } diff --git a/src/model/User.ts b/src/model/User.ts index 9a7a3d4..2b98e0e 100644 --- a/src/model/User.ts +++ b/src/model/User.ts @@ -2,10 +2,15 @@ export type authenticationData = { id: string } -export type TUser = { +export interface UserDTO{ id: string, name: string, email: string, password: string } +export interface InputControllerDTO{ + name: string, + email: string, + password: string + } \ No newline at end of file diff --git a/src/model/likes.ts b/src/model/likes.ts index fd6558b..fe2deed 100644 --- a/src/model/likes.ts +++ b/src/model/likes.ts @@ -1,9 +1,3 @@ -export type TLike= { - id: string, - postId: string, - authorId: string - -} export interface LikeInputDTO{ id: string, post_id: string, @@ -14,7 +8,10 @@ export interface LikeInputDataDTO{ id: string, postId: string, authorId: string - +} +export interface LikeInputControllerDTO{ + postId: string, + authorId: string } export interface DeleteLikeInputDTO{ id: string, From 2f181a2a71e6829fb94c35a491e3edca3f1a65d2 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Fri, 3 Feb 2023 15:26:06 -0300 Subject: [PATCH 08/22] Feat: se aplicado, este commit add as Routers --- request.rest | 28 +++++++------ src/controller/PostController.ts | 2 +- src/controller/app.ts | 13 ++++++ src/controller/router/FriendshipRouter.ts | 11 +++++ src/controller/router/commentsRouter.ts | 10 +++++ src/controller/router/likeRouter.ts | 11 +++++ src/controller/router/postRouter.ts | 13 ++++++ src/controller/router/userRouter.ts | 10 +++++ src/index.ts | 51 +++++------------------ 9 files changed, 96 insertions(+), 53 deletions(-) create mode 100644 src/controller/app.ts create mode 100644 src/controller/router/FriendshipRouter.ts create mode 100644 src/controller/router/commentsRouter.ts create mode 100644 src/controller/router/likeRouter.ts create mode 100644 src/controller/router/postRouter.ts create mode 100644 src/controller/router/userRouter.ts diff --git a/request.rest b/request.rest index 7333f64..20fd616 100644 --- a/request.rest +++ b/request.rest @@ -1,32 +1,36 @@ ### Create a new User -POST http://localhost:3003/users +POST http://localhost:3003/user/create Content-Type: application/json { - "name":"Bianca2 Smith", - "email":"bianca2@gmail.com", + "name":"Bianca5 Smith", + "email":"bianca5@gmail.com", "password": "1234567" } ### Return post -GET http://localhost:3003/posts/1675017838548 +GET http://localhost:3003/post/getpost Content-Type: application/json +{ + "id":"1675379034720" +} + ### Create a new Post -POST http://localhost:3003/post +POST http://localhost:3003/post/create Content-Type: application/json { "photo" : "Foto", "description": "foto da viagem", - "type": "event", + "type": "normal", "createdAt": "02/01/2023", "authorId": "1675081679184" } ### Create a new Friendship -POST http://localhost:3003/friendship +POST http://localhost:3003/friendship/create Content-Type: application/json { @@ -43,11 +47,11 @@ Content-Type: application/json } ### Return Feeds friends -GET http://localhost:3003/feeds/1675001631299 +GET http://localhost:3003/post/getfeeds/1675001631299 Content-Type: application/json ### return feed by type -GET http://localhost:3003/feeds +GET http://localhost:3003/post/getfeeds Content-Type: application/json { @@ -55,11 +59,11 @@ Content-Type: application/json } ### Like Post -POST http://localhost:3003/like +POST http://localhost:3003/like/create Content-Type: application/json { - "postId":"1675089703154", + "postId":"1675379034720", "authorId": "1675001631299" } @@ -68,7 +72,7 @@ DELETE http://localhost:3003/like/1675001631299 Content-Type: application/json { - "postId":"1675089703154" + "postId":"1675379034720" } ### Comment Post diff --git a/src/controller/PostController.ts b/src/controller/PostController.ts index 622f133..e159aeb 100644 --- a/src/controller/PostController.ts +++ b/src/controller/PostController.ts @@ -26,7 +26,7 @@ export class PostController { findPost = async (req: Request, res: Response): Promise => { try { const input: PostIdDTO = { - id: req.params.id + id: req.body.id }; const posts = await postBusiness.findPost(input) diff --git a/src/controller/app.ts b/src/controller/app.ts new file mode 100644 index 0000000..32e736f --- /dev/null +++ b/src/controller/app.ts @@ -0,0 +1,13 @@ +import express from 'express' +import cors from 'cors' + +const app = express() + +app.use(express.json()) +app.use(cors()) + +app.listen(3003, ()=>{ + console.log('Servidor rodando na porta 3003') +}) + +export default app \ No newline at end of file diff --git a/src/controller/router/FriendshipRouter.ts b/src/controller/router/FriendshipRouter.ts new file mode 100644 index 0000000..9c72840 --- /dev/null +++ b/src/controller/router/FriendshipRouter.ts @@ -0,0 +1,11 @@ +import express from "express"; + +import { FriendshipController } from "../FriendshipController"; + +export const friendshipRouter = express.Router() + +const friendshipController = new FriendshipController(); + +friendshipRouter.post('/create',friendshipController.createFriendship); +friendshipRouter.delete('/:id',friendshipController.deleteFriendship); + diff --git a/src/controller/router/commentsRouter.ts b/src/controller/router/commentsRouter.ts new file mode 100644 index 0000000..3c238db --- /dev/null +++ b/src/controller/router/commentsRouter.ts @@ -0,0 +1,10 @@ +import express from "express"; + +import { CommentController } from "../CommentsController"; + +export const commentsRouter = express.Router() + +const commentController = new CommentController(); + +commentsRouter.post('/', commentController.createComment); + diff --git a/src/controller/router/likeRouter.ts b/src/controller/router/likeRouter.ts new file mode 100644 index 0000000..f033a4f --- /dev/null +++ b/src/controller/router/likeRouter.ts @@ -0,0 +1,11 @@ +import express from "express"; + +import { LikeController } from "../LikeController"; + +export const likeRouter = express.Router() + +const likeController = new LikeController(); + +likeRouter.post('/create',likeController.createLike); +likeRouter.delete('/:id',likeController.deleteLike); + diff --git a/src/controller/router/postRouter.ts b/src/controller/router/postRouter.ts new file mode 100644 index 0000000..7d12d8c --- /dev/null +++ b/src/controller/router/postRouter.ts @@ -0,0 +1,13 @@ +import express from "express"; + +import { PostController } from "../PostController"; + +export const postRouter = express.Router() + +const postController = new PostController(); + +postRouter.post('/create',postController.createPost); +postRouter.get('/getpost',postController.findPost); +postRouter.get('/getfeeds/:id',postController.feedPost); +postRouter.get('/getfeeds',postController.feedPostAll); + diff --git a/src/controller/router/userRouter.ts b/src/controller/router/userRouter.ts new file mode 100644 index 0000000..7d47b43 --- /dev/null +++ b/src/controller/router/userRouter.ts @@ -0,0 +1,10 @@ +import express from "express"; + +import { UserController } from "../UserController"; + +export const userRouter = express.Router() + +const userController = new UserController(); + +userRouter.post('/create', userController.createUser); + diff --git a/src/index.ts b/src/index.ts index 668c5d7..9c90076 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,46 +1,17 @@ -import express, { Express } from "express" -import cors from "cors" -import { UserController } from "./controller/UserController" -import { PostController } from "./controller/PostController" -import { FriendshipController } from "./controller/FriendshipController" -import { LikeController } from "./controller/LikeController" -import { CommentController } from "./controller/CommentsController" +import app from "./controller/app" +import { userRouter } from "./controller/router/userRouter" +import { postRouter } from "./controller/router/postRouter" +import { friendshipRouter } from "./controller/router/FriendshipRouter" +import { likeRouter } from "./controller/router/likeRouter" +import { commentsRouter } from "./controller/router/commentsRouter" -/**************************** CONFIG ******************************/ - -const app: Express = express() -app.use(express.json()) -app.use(cors()) - -app.listen(3003, () => { - console.log("Server running on port 3003") -}) /**************************** ENDPOINTS ******************************/ -const userController = new UserController(); -const postController = new PostController(); -const friendshipController = new FriendshipController(); -const likeController = new LikeController(); -const commentController = new CommentController(); - -app.post('/users',userController.createUser); - -app.post('/post',postController.createPost); - -app.post('/friendship',friendshipController.createFriendship); - -app.post('/like',likeController.createLike); - -app.post('/comments', commentController.createComment); - -app.delete('/friendship/:id',friendshipController.deleteFriendship); - -app.delete('/like/:id',likeController.deleteLike); - -app.get('/posts/:id',postController.findPost); - -app.get('/feeds/:id',postController.feedPost); +app.use('/user', userRouter) +app.use('/post', postRouter); +app.use('/friendship', friendshipRouter); +app.use('/like', likeRouter); +app.use('/comments', commentsRouter); -app.get('/feeds',postController.feedPostAll); From 33cf77c839c56b521cb5e8c5a3ee4dc6c10230b1 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Fri, 3 Feb 2023 16:13:28 -0300 Subject: [PATCH 09/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 05f3929..b2506f1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Projeto desenvolvido como didática de back-end para as turmas JBL LABENU com co [Doc_Postman](https://documenter.getpostman.com/view/22363157/2s8Z75S9p9) ## Link Deploy Render -https://labsystem6.onrender.com +https://labook4.onrender.com ## 👩🏾Pessoas Desenvolvedoras do Projeto From 24744be9a0bc43b936b254513f0effb279fd258c Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Fri, 3 Feb 2023 17:00:18 -0300 Subject: [PATCH 10/22] Update FriendshipController.ts --- src/controller/FriendshipController.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/controller/FriendshipController.ts b/src/controller/FriendshipController.ts index 47323d6..f8cd817 100644 --- a/src/controller/FriendshipController.ts +++ b/src/controller/FriendshipController.ts @@ -1,6 +1,6 @@ import { Request, Response } from "express"; import { FriendshipBusiness } from "../business/FriendshipBusiness"; -import { FriendInputDTO } from "../model/friends"; +import { FriendInputDTO } from "../model/Friends"; import { DeleteFriendshipInputDTO } from "../model/Friendship"; const friendshipBusiness = new FriendshipBusiness(); export class FriendshipController { @@ -34,4 +34,4 @@ export class FriendshipController { res.status(400).send(error.message); } }; -} \ No newline at end of file +} From 10c800a478077cef02b978a44e741af2627fa0ac Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Fri, 3 Feb 2023 17:01:03 -0300 Subject: [PATCH 11/22] Update FriendshipBusiness.ts --- src/business/FriendshipBusiness.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index dc97fc9..3419492 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -1,6 +1,6 @@ import { FriendshipDatabase } from "../data/FriendshipDatabase"; import { UserDatabase } from "../data/UserDatabase"; -import { FriendInputDTO } from "../model/friends"; +import { FriendInputDTO } from "../model/Friends"; import { DeleteFriendshipInputDTO, FriendshipInputDTO From ca6e4ad4fb8cf125747966e87a398f334aa6d4d0 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Fri, 3 Feb 2023 17:08:22 -0300 Subject: [PATCH 12/22] Refactor:se aplicado, este commit corrige nome modal freind --- request.rest | 4 ++-- src/business/FriendshipBusiness.ts | 2 +- src/controller/FriendshipController.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/request.rest b/request.rest index 20fd616..d44cc48 100644 --- a/request.rest +++ b/request.rest @@ -4,8 +4,8 @@ POST http://localhost:3003/user/create Content-Type: application/json { - "name":"Bianca5 Smith", - "email":"bianca5@gmail.com", + "name":"Bianca6 Smith", + "email":"bianca6@gmail.com", "password": "1234567" } diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index 3419492..dc97fc9 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -1,6 +1,6 @@ import { FriendshipDatabase } from "../data/FriendshipDatabase"; import { UserDatabase } from "../data/UserDatabase"; -import { FriendInputDTO } from "../model/Friends"; +import { FriendInputDTO } from "../model/friends"; import { DeleteFriendshipInputDTO, FriendshipInputDTO diff --git a/src/controller/FriendshipController.ts b/src/controller/FriendshipController.ts index f8cd817..cb15f5a 100644 --- a/src/controller/FriendshipController.ts +++ b/src/controller/FriendshipController.ts @@ -1,6 +1,6 @@ import { Request, Response } from "express"; import { FriendshipBusiness } from "../business/FriendshipBusiness"; -import { FriendInputDTO } from "../model/Friends"; +import { FriendInputDTO } from "../model/friends"; import { DeleteFriendshipInputDTO } from "../model/Friendship"; const friendshipBusiness = new FriendshipBusiness(); export class FriendshipController { From 97969e179ababc98e498161b8772b05eacd4be29 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Fri, 3 Feb 2023 21:03:07 -0300 Subject: [PATCH 13/22] Refactor: se aplicado, este commit refatora todos os endPoints --- request.rest | 29 +++++++++++++---------- src/business/CommentsBusiness.ts | 2 +- src/business/FriendshipBusiness.ts | 5 +--- src/business/LikeBusiness.ts | 2 +- src/business/PostBusiness.ts | 10 ++++---- src/business/UserBusiness.ts | 6 ++--- src/controller/CommentsController.ts | 4 ++-- src/controller/FriendshipController.ts | 4 ++-- src/controller/LikeController.ts | 4 ++-- src/controller/PostController.ts | 6 ++--- src/controller/UserController.ts | 2 +- src/controller/router/FriendshipRouter.ts | 2 +- src/controller/router/likeRouter.ts | 2 +- src/controller/router/postRouter.ts | 2 +- src/data/PostDatabase.ts | 4 ++-- 15 files changed, 41 insertions(+), 43 deletions(-) diff --git a/request.rest b/request.rest index d44cc48..f2bf2ef 100644 --- a/request.rest +++ b/request.rest @@ -20,35 +20,37 @@ Content-Type: application/json ### Create a new Post POST http://localhost:3003/post/create Content-Type: application/json +Authorization: 1675001631299 { "photo" : "Foto", "description": "foto da viagem", "type": "normal", - "createdAt": "02/01/2023", - "authorId": "1675081679184" + "createdAt": "02/01/2023" } ### Create a new Friendship POST http://localhost:3003/friendship/create Content-Type: application/json +Authorization: 1675001631299 { - "friendId":"1675081679184", - "authorId": "1675001631299" + "friendId":"1675019596015" } ### Delete Friendship -DELETE http://localhost:3003/friendship/1675001631299 +DELETE http://localhost:3003/friendship Content-Type: application/json +Authorization: 1675001631299 { - "friendId":"1675081679184" + "friendId":"1675019596015" } -### Return Feeds friends -GET http://localhost:3003/post/getfeeds/1675001631299 +### Return Feeds freands +GET http://localhost:3003/post/getfeedsfreands Content-Type: application/json +Authorization: 1675001631299 ### return feed by type GET http://localhost:3003/post/getfeeds @@ -61,15 +63,16 @@ Content-Type: application/json ### Like Post POST http://localhost:3003/like/create Content-Type: application/json +Authorization: 1675001631299 { - "postId":"1675379034720", - "authorId": "1675001631299" + "postId":"1675379034720" } ### Delete Like Post -DELETE http://localhost:3003/like/1675001631299 +DELETE http://localhost:3003/like Content-Type: application/json +Authorization: 1675001631299 { "postId":"1675379034720" @@ -78,9 +81,9 @@ Content-Type: application/json ### Comment Post POST http://localhost:3003/comments Content-Type: application/json +Authorization: 1675001631299 { "comment":"Linda foto", - "postId":"1675379034720", - "authorId": "1675001631299" + "postId":"1675379034720" } \ No newline at end of file diff --git a/src/business/CommentsBusiness.ts b/src/business/CommentsBusiness.ts index 0c56103..89bbde2 100644 --- a/src/business/CommentsBusiness.ts +++ b/src/business/CommentsBusiness.ts @@ -14,7 +14,7 @@ export class CommentsBusiness { if (!comment || !postId || !authorId) { throw new Error( - 'Preencha os campos "comment", "postId" e "authorId"' + 'Fill in the fields "comment", "postId" and "authorId"' ); } diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index dc97fc9..372199a 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -1,10 +1,7 @@ import { FriendshipDatabase } from "../data/FriendshipDatabase"; import { UserDatabase } from "../data/UserDatabase"; import { FriendInputDTO } from "../model/friends"; -import { - DeleteFriendshipInputDTO, - FriendshipInputDTO -} from "../model/Friendship"; +import { DeleteFriendshipInputDTO, FriendshipInputDTO} from "../model/Friendship"; const friendshipDatabase = new FriendshipDatabase(); const userDatabase = new UserDatabase(); diff --git a/src/business/LikeBusiness.ts b/src/business/LikeBusiness.ts index db146fd..583969d 100644 --- a/src/business/LikeBusiness.ts +++ b/src/business/LikeBusiness.ts @@ -1,7 +1,7 @@ import { LikeDatabase } from "../data/LikeDatabase"; import { PostDatabase } from "../data/PostDatabase"; import { UserDatabase } from "../data/UserDatabase"; -import { LikeInputControllerDTO, LikeInputDataDTO, LikeInputDTO } from "../model/likes"; +import { LikeInputControllerDTO, LikeInputDTO } from "../model/likes"; const likeDatabase = new LikeDatabase(); const userDatabase = new UserDatabase(); diff --git a/src/business/PostBusiness.ts b/src/business/PostBusiness.ts index 8585706..4a86fa3 100644 --- a/src/business/PostBusiness.ts +++ b/src/business/PostBusiness.ts @@ -16,14 +16,14 @@ export class PostBusiness { if (!photo || !description || !type || !createdAt || !authorId) { throw new Error( - 'Preencha os campos photo, description, type, authorId' + 'Fill in the fields photo, description, type, authorId' ); } if(type.toUpperCase() !== "normal".toUpperCase() && type.toUpperCase() !== "event".toUpperCase()){ throw new Error( - 'Preencha o campo type com normal ou event' + 'Fill in the fields type: normal or event' ); } @@ -60,9 +60,7 @@ export class PostBusiness { const { id } = input; if(!id){ - throw new Error( - 'Pass the id params' - ); + throw new Error('Pass the id params'); } const result:TPost[] = await postDatabase.findPost(id) @@ -133,7 +131,7 @@ export class PostBusiness { if(type.toUpperCase() !== "normal".toUpperCase() && type.toUpperCase() !== "event".toUpperCase()){ throw new Error( - 'Preencha o campo type com normal ou event' + 'Fill in the field type: normal or event' ); } const posts: FeedPostDTO[] = []; diff --git a/src/business/UserBusiness.ts b/src/business/UserBusiness.ts index ffb8932..52a0a14 100644 --- a/src/business/UserBusiness.ts +++ b/src/business/UserBusiness.ts @@ -10,19 +10,19 @@ export class UserBusiness { if (!name || !email || !password) { throw new Error( - 'Preencha os campos "name", "email" e "password"' + 'Fill in the fields "name", "email" e "password"' ); } if (password.length < 6) { - throw new Error("Senha muito curta"); + throw new Error("Password too short minimum 6 characters"); } const userBase = await userDatabase.findUser(); const existUser = userBase.findIndex((user)=>user.email === email) if(existUser != -1) { - throw new Error("Usuário já cadastrado "); + throw new Error("User already registered"); } const id: string = Date.now().toString(); diff --git a/src/controller/CommentsController.ts b/src/controller/CommentsController.ts index 0a77d9c..f3e8358 100644 --- a/src/controller/CommentsController.ts +++ b/src/controller/CommentsController.ts @@ -8,13 +8,13 @@ export class CommentController { const input: InputCommentControllerDTO = { comment: req.body.comment, postId: req.body.postId, - authorId: req.body.authorId + authorId: req.headers.authorization as string }; const commentBusiness = new CommentsBusiness() await commentBusiness.createComment(input) - res.status(201).send({ message: "Comment create!" }); + res.status(201).send({ message: "Comment created!" }); } catch (error: any) { res.status(400).send(error.message); } diff --git a/src/controller/FriendshipController.ts b/src/controller/FriendshipController.ts index cb15f5a..1b45a8a 100644 --- a/src/controller/FriendshipController.ts +++ b/src/controller/FriendshipController.ts @@ -8,7 +8,7 @@ export class FriendshipController { try { const input: FriendInputDTO = { friendId: req.body.friendId, - authorId: req.body.authorId + authorId: req.headers.authorization as string }; await friendshipBusiness.createFriendship(input) @@ -25,7 +25,7 @@ export class FriendshipController { try { const input: DeleteFriendshipInputDTO = { friendId: req.body.friendId, - authorId: req.params.id + authorId: req.headers.authorization as string }; await friendshipBusiness.deleteFriendship(input) diff --git a/src/controller/LikeController.ts b/src/controller/LikeController.ts index 2f43681..88eb9b4 100644 --- a/src/controller/LikeController.ts +++ b/src/controller/LikeController.ts @@ -8,7 +8,7 @@ export class LikeController { try { const input: LikeInputControllerDTO = { postId: req.body.postId, - authorId: req.body.authorId + authorId: req.headers.authorization as string }; await likeBusiness.createLike(input) @@ -25,7 +25,7 @@ export class LikeController { try { const input: LikeInputControllerDTO = { postId: req.body.postId, - authorId: req.params.id + authorId: req.headers.authorization as string }; await likeBusiness.deleteLike(input) diff --git a/src/controller/PostController.ts b/src/controller/PostController.ts index e159aeb..ee059ac 100644 --- a/src/controller/PostController.ts +++ b/src/controller/PostController.ts @@ -12,12 +12,12 @@ export class PostController { description:req.body.description, type: req.body.type, createdAt: req.body.createdAt, - authorId: req.body.authorId + authorId: req.headers.authorization as string }; await postBusiness.createPost(input) - res.status(201).send({ message: "Post criado!" }); + res.status(201).send({ message: "Post created!" }); } catch (error: any) { res.status(400).send(error.message); } @@ -40,7 +40,7 @@ export class PostController { feedPost = async(req: Request, res: Response) => { try { const input: PostIdDTO = { - id: req.params.id + id: req.headers.authorization as string }; const posts = await postBusiness.feedPost(input) diff --git a/src/controller/UserController.ts b/src/controller/UserController.ts index 0421655..b3ce7d5 100644 --- a/src/controller/UserController.ts +++ b/src/controller/UserController.ts @@ -14,7 +14,7 @@ export class UserController { const userBusiness = new UserBusiness() await userBusiness.createUser(input) - res.status(201).send({ message: "Usuário criado!" }); + res.status(201).send({ message: "User created!" }); } catch (error: any) { res.status(400).send(error.message); } diff --git a/src/controller/router/FriendshipRouter.ts b/src/controller/router/FriendshipRouter.ts index 9c72840..a43c44b 100644 --- a/src/controller/router/FriendshipRouter.ts +++ b/src/controller/router/FriendshipRouter.ts @@ -7,5 +7,5 @@ export const friendshipRouter = express.Router() const friendshipController = new FriendshipController(); friendshipRouter.post('/create',friendshipController.createFriendship); -friendshipRouter.delete('/:id',friendshipController.deleteFriendship); +friendshipRouter.delete('/',friendshipController.deleteFriendship); diff --git a/src/controller/router/likeRouter.ts b/src/controller/router/likeRouter.ts index f033a4f..8f58943 100644 --- a/src/controller/router/likeRouter.ts +++ b/src/controller/router/likeRouter.ts @@ -7,5 +7,5 @@ export const likeRouter = express.Router() const likeController = new LikeController(); likeRouter.post('/create',likeController.createLike); -likeRouter.delete('/:id',likeController.deleteLike); +likeRouter.delete('/',likeController.deleteLike); diff --git a/src/controller/router/postRouter.ts b/src/controller/router/postRouter.ts index 7d12d8c..d4d4df1 100644 --- a/src/controller/router/postRouter.ts +++ b/src/controller/router/postRouter.ts @@ -8,6 +8,6 @@ const postController = new PostController(); postRouter.post('/create',postController.createPost); postRouter.get('/getpost',postController.findPost); -postRouter.get('/getfeeds/:id',postController.feedPost); +postRouter.get('/getfeedsfreands',postController.feedPost); postRouter.get('/getfeeds',postController.feedPostAll); diff --git a/src/data/PostDatabase.ts b/src/data/PostDatabase.ts index 6a1166e..de5c145 100644 --- a/src/data/PostDatabase.ts +++ b/src/data/PostDatabase.ts @@ -37,7 +37,7 @@ export class PostDatabase extends BaseDatabase { feedPost = async (input: string[]): Promise => { try { const [result] = await PostDatabase.connection.raw( - `select * from ${PostDatabase.TABLE_NAME} where author_id in (${input}) order by created_at;` + `select * from ${PostDatabase.TABLE_NAME} where author_id in (${input}) order by created_at desc;` ); return result; } catch (error: any) { @@ -48,7 +48,7 @@ export class PostDatabase extends BaseDatabase { feedPostAll = async (input: PostTypeDTO): Promise => { try { const [result] = await PostDatabase.connection.raw( - `select * from ${PostDatabase.TABLE_NAME} where type = "${input.type}" order by created_at;` + `select * from ${PostDatabase.TABLE_NAME} where type = "${input.type}" order by created_at desc;` ); return result; } catch (error: any) { From c9aa8298152726b38cfcfc9db20b1582b862ef41 Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Fri, 3 Feb 2023 21:11:39 -0300 Subject: [PATCH 14/22] Refactor: se aplicado, este commit corrige bug no request --- request.rest | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/request.rest b/request.rest index f2bf2ef..36c7bb7 100644 --- a/request.rest +++ b/request.rest @@ -4,8 +4,8 @@ POST http://localhost:3003/user/create Content-Type: application/json { - "name":"Bianca6 Smith", - "email":"bianca6@gmail.com", + "name":"Bianca Smith", + "email":"bianca9@gmail.com", "password": "1234567" } @@ -26,7 +26,7 @@ Authorization: 1675001631299 "photo" : "Foto", "description": "foto da viagem", "type": "normal", - "createdAt": "02/01/2023" + "createdAt": "08/02/2023" } ### Create a new Friendship From a21e394bb9959964c9a79efb53355d447b561fb7 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Fri, 3 Feb 2023 22:09:52 -0300 Subject: [PATCH 15/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2506f1..4daa3b3 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Repositório do projeto Labook Projeto desenvolvido como didática de back-end para as turmas JBL LABENU com conteúdos que englobam o universo da criação de uma API com a temática de um sistema de gerenciamento básico da organizaçãode labenu. ## Link Documentação Postman -[Doc_Postman](https://documenter.getpostman.com/view/22363157/2s8Z75S9p9) +[Doc_Postman](https://documenter.getpostman.com/view/22363157/2s935mtRKC) ## Link Deploy Render https://labook4.onrender.com From 1582a3b5578bc8ab66a22a70c9d834d842b1ce69 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Sat, 4 Feb 2023 10:10:41 -0300 Subject: [PATCH 16/22] Update README.md --- README.md | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 4daa3b3..1b8fbc1 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,7 @@ -# labook-template -Repositório do projeto Labook - ##

📇 Labook

## :memo: Descrição -Projeto desenvolvido como didática de back-end para as turmas JBL LABENU com conteúdos que englobam o universo da criação de uma API com a temática de um sistema de gerenciamento básico da organizaçãode labenu. +Projeto desenvolvido como didática de back-end para as turmas JBL LABENU com conteúdos que englobam o universo da criação de APIs com a temática de um rede social. ## Link Documentação Postman [Doc_Postman](https://documenter.getpostman.com/view/22363157/2s935mtRKC) @@ -17,16 +14,16 @@ https://labook4.onrender.com [
Byron Smith](https://github.com/byron-smith-nobrega) ## :books: Funcionalidades -* Criar Estudantes: Métodos voltados para a criação de usuários que são estudantes. -* Buscar Estudantes: Métodos voltados para a consulta de estudantes cadastradas. -* Mudar Estudantes de Turma: Métodos voltados para a alteração do estudante de turma. -* Criar Docentes: Métodos voltados para a criação de usuários que são pessoas instrutora. -* Buscar Docentes: Métodos voltados para a consulta de pessoas instrutoras cadastradas. -* Mudar Docente de Turma: Métodos voltados para a alteração do docente de turma. -* Criar Turma: Métodos para a criação de turmas. -* Buscar Turma: Métodos que realiza busca em banco das turmas ativas. -* Mudar Turma Módulo: Métodos voltados para a alteração da turma de mód. - +* Criar Usuário: Método voltado para a criação de usuários. +* Criar Post: Método voltado para a criação de postagens. +* Buscar Post: Método voltado para a consulta de uma postagem. +* Criar Amizade: Método voltado para a criação de amizade entre usuários. +* Deletar Amizade: Método voltado para a exclusão de uma amizade. +* Criar Curtida: Método voltado para a criação de vínculo entre usuário e postagem. +* Deletar Curtida: Método voltado para a exclusão de vínculo entre usuário e postagem. +* Criar Comentário : Método voltado para a criação de comentário nas postagens. +* Buscar Feeds Amigos : Método voltado para a consulta de postagens dos amigos. +* Buscar Feeds: Método voltado para a consulta de postagens. ## :wrench: Tecnologias utilizadas * VS Code From 4f1608eb42806fc0ed91dca07e452dab5b986ac4 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Sat, 4 Feb 2023 10:11:44 -0300 Subject: [PATCH 17/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1b8fbc1..c60f028 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Projeto desenvolvido como didática de back-end para as turmas JBL LABENU com co ## Link Deploy Render https://labook4.onrender.com -## 👩🏾Pessoas Desenvolvedoras do Projeto +## 👩🏾Pessoa Desenvolvedora do Projeto [
Byron Smith](https://github.com/byron-smith-nobrega) From 73201163ac5f1ed544e6b7d5465f5f0a657f608f Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Sat, 4 Feb 2023 11:04:08 -0300 Subject: [PATCH 18/22] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c60f028..20aca8f 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ https://labook4.onrender.com * axios * cors * dotenv +* uuid * MySQL From 729d9e4df4b9303ead8fba4d54f6326736c2a45f Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Sat, 4 Feb 2023 14:32:52 -0300 Subject: [PATCH 19/22] =?UTF-8?q?Refactor:=20se=20aplicado,=20este=20commi?= =?UTF-8?q?t=20add=20fun=C3=A7=C3=A3o=20idGenerator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- request.rest | 2 +- src/business/CommentsBusiness.ts | 5 ++- src/business/FriendshipBusiness.ts | 4 ++- src/business/LikeBusiness.ts | 4 ++- src/business/PostBusiness.ts | 4 ++- src/business/UserBusiness.ts | 4 ++- src/data/TableDataBase.ts | 55 ++++++++++++++++++++++++++++++ src/data/connection.ts | 18 ---------- src/data/migrations.ts | 45 ++++-------------------- src/service/IdGenerator.ts | 6 ++++ 11 files changed, 86 insertions(+), 63 deletions(-) create mode 100644 src/data/TableDataBase.ts delete mode 100644 src/data/connection.ts create mode 100644 src/service/IdGenerator.ts diff --git a/package.json b/package.json index 2e0e6ce..20a6081 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "start": "tsc && node ./build/index.js", "dev": "ts-node-dev ./src/index.ts", - "migrations": "tsc && node ./build/dataBase/migrations.js" + "migrations": "tsc && node ./build/data/migrations.js" }, "author": "Byron", "license": "ISC", diff --git a/request.rest b/request.rest index 36c7bb7..868a3c0 100644 --- a/request.rest +++ b/request.rest @@ -5,7 +5,7 @@ Content-Type: application/json { "name":"Bianca Smith", - "email":"bianca9@gmail.com", + "email":"biancasmith@gmail.com", "password": "1234567" } diff --git a/src/business/CommentsBusiness.ts b/src/business/CommentsBusiness.ts index 89bbde2..1eb1501 100644 --- a/src/business/CommentsBusiness.ts +++ b/src/business/CommentsBusiness.ts @@ -2,9 +2,12 @@ import { CommentDatabase } from "../data/CommentsDatabase"; import { PostDatabase } from "../data/PostDatabase"; import { UserDatabase } from "../data/UserDatabase"; import { InputCommentControllerDTO } from "../model/Comments"; +import { IdGenerator } from "../service/IdGenerator"; + const commentDatabase = new CommentDatabase(); const userDatabase = new UserDatabase(); const postDatabase = new PostDatabase(); +const idGenerator = new IdGenerator(); export class CommentsBusiness { createComment = async (input: InputCommentControllerDTO): Promise => { @@ -31,7 +34,7 @@ export class CommentsBusiness { throw new Error("Post not exist."); } - const id: string = Date.now().toString(); + const id: string = idGenerator.generateId(); await commentDatabase.insertcomment({ diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index 372199a..caad450 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -2,9 +2,11 @@ import { FriendshipDatabase } from "../data/FriendshipDatabase"; import { UserDatabase } from "../data/UserDatabase"; import { FriendInputDTO } from "../model/friends"; import { DeleteFriendshipInputDTO, FriendshipInputDTO} from "../model/Friendship"; +import { IdGenerator } from "../service/IdGenerator"; const friendshipDatabase = new FriendshipDatabase(); const userDatabase = new UserDatabase(); +const idGenerator = new IdGenerator(); export class FriendshipBusiness { createFriendship = async (input: FriendInputDTO): Promise => { @@ -32,7 +34,7 @@ export class FriendshipBusiness { throw new Error("User id does not exist."); } - const id: string = Date.now().toString(); + const id: string = idGenerator.generateId(); const queryResult: FriendshipInputDTO[] = await friendshipDatabase.findFriendship(authorId); diff --git a/src/business/LikeBusiness.ts b/src/business/LikeBusiness.ts index 583969d..3e047c7 100644 --- a/src/business/LikeBusiness.ts +++ b/src/business/LikeBusiness.ts @@ -2,10 +2,12 @@ import { LikeDatabase } from "../data/LikeDatabase"; import { PostDatabase } from "../data/PostDatabase"; import { UserDatabase } from "../data/UserDatabase"; import { LikeInputControllerDTO, LikeInputDTO } from "../model/likes"; +import { IdGenerator } from "../service/IdGenerator"; const likeDatabase = new LikeDatabase(); const userDatabase = new UserDatabase(); const postDatabase = new PostDatabase(); +const idGenerator = new IdGenerator(); export class LikeBusiness { createLike = async (input: LikeInputControllerDTO): Promise => { @@ -45,7 +47,7 @@ export class LikeBusiness { } - const id: string = Date.now().toString(); + const id: string = idGenerator.generateId(); await likeDatabase.insertLike({ id, diff --git a/src/business/PostBusiness.ts b/src/business/PostBusiness.ts index 4a86fa3..7229e29 100644 --- a/src/business/PostBusiness.ts +++ b/src/business/PostBusiness.ts @@ -4,10 +4,12 @@ import { UserDatabase } from "../data/UserDatabase"; import { FriendshipInputDTO } from "../model/Friendship"; import { FeedPostDBDTO, FeedPostDTO, InpultPostDTO, PostIdDTO, PostTypeDTO, TPost } from "../model/Posts"; import { dateFormat, dateFormatBr } from "../service/formatDate"; +import { IdGenerator } from "../service/IdGenerator"; const postDatabase = new PostDatabase(); const userDatabase = new UserDatabase(); const friendshipDatabase = new FriendshipDatabase(); +const idGenerator = new IdGenerator(); export class PostBusiness { createPost = async (input: InpultPostDTO): Promise => { @@ -38,7 +40,7 @@ export class PostBusiness { const formatDate:any= dateFormat(createdAt.toString()) - const id: string = Date.now().toString(); + const id: string = idGenerator.generateId(); await postDatabase.insertPost({ id, diff --git a/src/business/UserBusiness.ts b/src/business/UserBusiness.ts index 52a0a14..f37b5a3 100644 --- a/src/business/UserBusiness.ts +++ b/src/business/UserBusiness.ts @@ -1,5 +1,7 @@ import { UserDatabase } from "../data/UserDatabase"; import { InputControllerDTO } from "../model/User"; +import { IdGenerator } from "../service/IdGenerator"; +const idGenerator = new IdGenerator(); export class UserBusiness { createUser = async (input: InputControllerDTO): Promise => { @@ -24,7 +26,7 @@ export class UserBusiness { if(existUser != -1) { throw new Error("User already registered"); } - const id: string = Date.now().toString(); + const id: string = idGenerator.generateId(); await userDatabase.insertUser({ diff --git a/src/data/TableDataBase.ts b/src/data/TableDataBase.ts new file mode 100644 index 0000000..ea1c1c8 --- /dev/null +++ b/src/data/TableDataBase.ts @@ -0,0 +1,55 @@ +import { BaseDatabase } from "./BaseDatabase"; + +export class Migration extends BaseDatabase { + createTables = async () => { + try { + await Migration.connection + .raw(` + CREATE TABLE IF NOT EXISTS labook_users( + id VARCHAR(255) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + password VARCHAR(255) NOT NULL + ); + CREATE TABLE IF NOT EXISTS labook_posts( + id VARCHAR(255) PRIMARY KEY, + photo VARCHAR(255) NOT NULL, + description VARCHAR(255) NOT NULL, + type ENUM("normal","event") DEFAULT "normal", + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + author_id VARCHAR(255), + FOREIGN KEY (author_id) REFERENCES labook_users (id) + ); + CREATE TABLE IF NOT EXISTS labook_friendship( + id VARCHAR(255) PRIMARY KEY, + friend_id VARCHAR(255) NOT NULL, + author_id VARCHAR(255) NOT NULL, + FOREIGN KEY (author_id) REFERENCES labook_users (id), + FOREIGN KEY (friend_id) REFERENCES labook_users (id) + ); + CREATE TABLE IF NOT EXISTS labook_likes( + id VARCHAR(255) PRIMARY KEY, + post_id VARCHAR(255) NOT NULL, + author_id VARCHAR(255) NOT NULL, + FOREIGN KEY (author_id) REFERENCES labook_users (id), + FOREIGN KEY (post_id) REFERENCES labook_posts (id) + ); + CREATE TABLE IF NOT EXISTS labook_comments( + id VARCHAR(255) PRIMARY KEY, + comment TEXT(500) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + post_id VARCHAR(255) NOT NULL, + author_id VARCHAR(255) NOT NULL, + FOREIGN KEY (author_id) REFERENCES labook_users (id), + FOREIGN KEY (post_id) REFERENCES labook_posts (id) + ); + `) + } catch (error: any) { + throw new Error(error.message); + } + }; +} + +const printError = (error: any) => { + console.log(error.sqlMessage || error.message); +}; diff --git a/src/data/connection.ts b/src/data/connection.ts deleted file mode 100644 index badde9c..0000000 --- a/src/data/connection.ts +++ /dev/null @@ -1,18 +0,0 @@ -import knex from "knex" -import dotenv from "dotenv" - -dotenv.config() - -const connection = knex({ - client: "mysql", - connection: { - host: process.env.DB_HOST, - port: 3306, - user: process.env.DB_USER, - password: process.env.DB_PASSWORD, - database: process.env.DB_DATABASE, - multipleStatements: true - }, -}); - -export default connection \ No newline at end of file diff --git a/src/data/migrations.ts b/src/data/migrations.ts index 1dfeb40..a7b0a5f 100644 --- a/src/data/migrations.ts +++ b/src/data/migrations.ts @@ -1,41 +1,10 @@ -import connection from "./connection" -const createTables = async () => { - await connection.raw(` - CREATE TABLE IF NOT EXISTS labook_users( - id VARCHAR(255) PRIMARY KEY, - name VARCHAR(255) NOT NULL, - email VARCHAR(255) UNIQUE NOT NULL, - password VARCHAR(255) NOT NULL - ); +import { Migration } from "./TableDataBase" +const migration = new Migration(); - CREATE TABLE IF NOT EXISTS labook_posts( - id VARCHAR(255) PRIMARY KEY, - photo VARCHAR(255) NOT NULL, - description VARCHAR(255) NOT NULL, - type ENUM("normal","event") DEFAULT "normal", - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - author_id VARCHAR(255), - FOREIGN KEY (author_id) REFERENCES labook_users (id) - ) - - CREATE TABLE IF NOT EXISTS labook_friendship( - id VARCHAR(255) PRIMARY KEY, - friend_id VARCHAR(255) NOT NULL, - author_id VARCHAR(255) NOT NULL, - FOREIGN KEY (author_id) REFERENCES labook_users (id), - FOREIGN KEY (friend_id) REFERENCES labook_users (id) - ) - - `) - .then(() => { - console.log(`Tables created successfully!`) - - }) - .catch((error: any) => printError(error)) -} - -const printError = (error: any) => { - console.log(error.sqlMessage || error.message) +const queryMigrations = ()=>{ + migration.createTables(); + console.log("Tabelas criadas!!"); + } -createTables() +queryMigrations(); \ No newline at end of file diff --git a/src/service/IdGenerator.ts b/src/service/IdGenerator.ts new file mode 100644 index 0000000..b36379b --- /dev/null +++ b/src/service/IdGenerator.ts @@ -0,0 +1,6 @@ +import { v4 } from "uuid"; + +export class IdGenerator { + + public generateId = () => v4() +} \ No newline at end of file From 90749e14944c29608afb213c7fbfeaf83fcae640 Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Sat, 4 Feb 2023 16:36:01 -0300 Subject: [PATCH 20/22] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 20aca8f..f6e00f7 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,13 @@ DB_USER = "" DB_PASS = "" DB_NAME = "" ``` -Após configuração do .env, dê o comando seguinte para rodar o migration: +Após configuração do .env, dê o comando seguinte para rodar a aplicação: ``` -npm run migrations +npm run start ``` -Após o migration, dê o comando seguinte para rodar a aplicação: +Após o start, dê o comando seguinte para criar as tabelas no banco de dados: ``` -npm run start +npm run migrations ``` Use o Postman ou o Insomnia para realizar as requisições desejadas. From a3248f7c481fa6c51ac97cd53f5b0b9703f14ecd Mon Sep 17 00:00:00 2001 From: Byron Belizario Smith Nobrega Date: Sun, 5 Feb 2023 08:16:52 -0300 Subject: [PATCH 21/22] Refactor: se aplicado, este commit corrige bug do postDatabase --- request.rest | 2 +- src/data/PostDatabase.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/request.rest b/request.rest index 868a3c0..c86d229 100644 --- a/request.rest +++ b/request.rest @@ -50,7 +50,7 @@ Authorization: 1675001631299 ### Return Feeds freands GET http://localhost:3003/post/getfeedsfreands Content-Type: application/json -Authorization: 1675001631299 +Authorization: fde08a25-cb5c-4948-bb59-693eb726721d ### return feed by type GET http://localhost:3003/post/getfeeds diff --git a/src/data/PostDatabase.ts b/src/data/PostDatabase.ts index de5c145..4a30b00 100644 --- a/src/data/PostDatabase.ts +++ b/src/data/PostDatabase.ts @@ -37,7 +37,7 @@ export class PostDatabase extends BaseDatabase { feedPost = async (input: string[]): Promise => { try { const [result] = await PostDatabase.connection.raw( - `select * from ${PostDatabase.TABLE_NAME} where author_id in (${input}) order by created_at desc;` + `select * from ${PostDatabase.TABLE_NAME} where author_id in ('${input}') order by created_at desc;` ); return result; } catch (error: any) { From fb89c8462347e0c03eb0e1ce45121c9cbfaa57eb Mon Sep 17 00:00:00 2001 From: Byron Smith <74737156+byron-smith-nobrega@users.noreply.github.com> Date: Sun, 5 Feb 2023 08:44:17 -0300 Subject: [PATCH 22/22] Update FriendshipBusiness.ts --- src/business/FriendshipBusiness.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/business/FriendshipBusiness.ts b/src/business/FriendshipBusiness.ts index caad450..010a6b5 100644 --- a/src/business/FriendshipBusiness.ts +++ b/src/business/FriendshipBusiness.ts @@ -46,7 +46,7 @@ export class FriendshipBusiness { if (existFriendship != -1) { throw new Error("friendship already exists!"); } - const idFriend: string = Date.now().toString(); + const idFriend: string = idGenerator.generateId(); await friendshipDatabase.insertPost({ id,