Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
build
.env
2,669 changes: 2,669 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

39 changes: 39 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "arquitetura-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "ts-node index.ts",
"start:dev": "ts-node-dev index.ts",
"build": "tsc index.ts",
"build:run": "tsc index.ts && node index.js"
},
"keywords": [
"mvc"
],
"author": "labenu",
"license": "ISC",
"dependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.7",
"@types/jsonwebtoken": "^8.5.0",
"@types/knex": "^0.16.1",
"@types/node": "^14.6.0",
"@types/uuid": "^8.3.0",
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"knex": "^0.21.5-next2",
"moment": "^2.29.0",
"mysql": "^2.18.1",
"ts-node": "^8.10.2",
"typescript": "^3.9.7",
"uuid": "^8.3.0"
},
"devDependencies": {
"ts-node-dev": "^1.0.0-pre.57"
}
}
42 changes: 42 additions & 0 deletions src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { UserDatabase } from "../data/UserDatabase";
import { Authenticator } from "../services/Authenticator";
import { HashManager } from "../services/HashManager";
import { IdGenerator } from "../services/IdGenerator";

export class UserBusiness {

public signup = async (name: string, email: string, password: string)=> {
if(!name || !email || !password) {
throw new Error('Insira todas as informações necessárias para o cadastro');
}//regra de negocio
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lembre de remover os comentários!


if(password.length < 6) {
throw new Error('A senha deve conter no mínimo seis caracteres')
}//regra de negocio




const idGenerator = new IdGenerator();
const id = idGenerator.generateId();

const hashManager = new HashManager();
const hashPassword = await hashManager.hash(password);

const userDataBase = new UserDatabase();


await userDataBase.createUser(
id,
name,
email,
hashPassword
);

const authenticator = new Authenticator();
const token = authenticator.generateToken({id});

return token;
}

}
26 changes: 26 additions & 0 deletions src/business/UserloginBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { UserDatabase } from "../data/UserDatabase";
import { Authenticator } from "../services/Authenticator";
import { HashManager } from "../services/HashManager";
import { IdGenerator } from "../services/IdGenerator";

export class UserloginBusiness {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Talvez essa classe possa ser absorvida pela UserBusiness


public login = async (email: string, password: string)=> {
const userDataBase = new UserDatabase();
const user = await userDataBase.getUserByEmail(email);

const hashManager = new HashManager();
const isPasswordCorrect = await hashManager.compare(password, user.password);

if(!isPasswordCorrect) {
throw new Error('Usuário ou senha errados');
}// regra de negocio

const authenticator = new Authenticator();
const token = authenticator.generateToken({
id: user.id
});
return token
}

}
23 changes: 23 additions & 0 deletions src/controller/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {Request, Response} from "express";
import {BaseDatabase} from "../data/BaseDatabase";
import { UserloginBusiness } from "../business/UserloginBusiness";

export const login = async (req: Request, res: Response)=>{
try {
const email = req.body.email;
const password = req.body.password;

const userBusiness = new UserloginBusiness();
const token= await userBusiness.login( email, password);

res.status(200).send({
message: 'Usuário logado com sucesso',
token
})
} catch (e) {
res.status(400).send({
message: e.message
})
}
await BaseDatabase.destroyConnection();
};
42 changes: 42 additions & 0 deletions src/controller/makeFriends.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {Request, Response} from "express";
import {Authenticator} from "../services/Authenticator";
import {UserDatabase} from "../data/UserDatabase";
import {BooksRelationDatabase} from "../data/BooksRelationDatabase";
import {BaseDatabase} from "../data/BaseDatabase";

export const followUser = async (req: Request, res: Response) => {
try {
const token = req.headers.authorization as string;
const amizadeId = req.body.amizadeId;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cuidado ao misturar idiomas nos nomes de variável.


const authenticator = new Authenticator();
const authenticationData = authenticator.verify(token);
const userId = authenticationData.id;

if(!amizadeId) {
throw new Error('Insira um id válido')
}
Comment on lines +16 to +18
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boa Validação!


const userDataBase = new UserDatabase();
const user = await userDataBase.getUserByEmail(amizadeId);

if(!user) {
throw new Error('Usuário não existe')
}
Comment on lines +21 to +25
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Outra excelente validação!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uma outra boa é checar se a amizade já existe antes de criar.


const bookRelationDatabase = new BooksRelationDatabase();
await bookRelationDatabase.amizadeUser(
userId,
amizadeId
);

res.status(200).send({
message: 'Usuário seguido com sucesso'
})
} catch (e) {
res.status(400).send({
message: e.message
})
}
await BaseDatabase.destroyConnection();
};
39 changes: 39 additions & 0 deletions src/controller/newPost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {Request, Response} from "express";
import {BaseDatabase} from "../data/BaseDatabase";
import {Authenticator} from "../services/Authenticator";
import {IdGenerator} from "../services/IdGenerator";
import {postDatabase} from "../data/postDatabase";

export const newPost = async (req: Request, res: Response) => {
try {
const token = req.headers.authorization as string;
const authenticator = new Authenticator();
const authenticationData = authenticator.verify(token);
const userId = authenticationData.id;

const idGenerator = new IdGenerator();
Comment on lines +9 to +14
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aqui seria interessante manter o padrão das classes de user e jogar as dependências para a classe de business.

const postId = idGenerator.generateId();

const {foto, descripcao, tipo} = req.body;
const creationDate = Date.now(); //gera um timestamp pega a data de ese moment exacto

const PostDatabase = new postDatabase(); // crio meu query para o banco de dados
await PostDatabase.criandopost(

postId,
userId,
foto,
descripcao,
creationDate,
tipo
);
res.status(200).send({
message: 'Post criado com sucesso'
})
} catch (e) {
res.status(400).send({
message: e.message
})
}
await BaseDatabase.destroyConnection();
};
8 changes: 8 additions & 0 deletions src/controller/onlyPostFeed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {request, response} from 'express'
import {BaseDatabase} from '../data/BaseDatabase'

export const onlyPostFeed = async(req: Request, res: Response)=> {



}
8 changes: 8 additions & 0 deletions src/controller/removeFriend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {request, response} from 'express'
import {BaseDatabase} from '../data/BaseDatabase'

export const removefriend = async(req: Request, res: Response)=> {



}
31 changes: 31 additions & 0 deletions src/controller/seeFeed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {Request, Response} from "express";
import {BaseDatabase} from "../data/BaseDatabase";
import {Authenticator} from "../services/Authenticator";
import {FeedDatabase} from "../data/seefeedDatabase";
import moment from "moment";

export const seefeed = async (req: Request, res: Response) => {
try {
const token = req.headers.authorization as string;
const authenticator = new Authenticator();
const authenticationData = authenticator.verify(token);
const userId = authenticationData.id;

const feedDatabase = new FeedDatabase();
const feed = await feedDatabase.getFeed(userId);
const mappedFeed = feed.map((item: any) => ({
id: item.recipe_id,
title: item.title,
description: item.description,
createdAt: moment(item.createdAt).format('DD/MM/YYYY'),
userId: item.id,
userName: item.name
}));
res.status(200).send(mappedFeed);
} catch (e) {
res.status(400).send({
message: e.message
})
}
await BaseDatabase.destroyConnection();
};
33 changes: 33 additions & 0 deletions src/controller/signUp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {Request, Response} from "express";
import {IdGenerator} from "../services/IdGenerator";
import {HashManager} from "../services/HashManager";
import {UserDatabase} from "../data/UserDatabase";
import {Authenticator} from "../services/Authenticator";
import {BaseDatabase} from "../data/BaseDatabase";
import {UserBusiness} from '../business/UserBusiness'

export const signup = async (req: Request, res: Response) => {



try {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;

const userBusiness = new UserBusiness();
const token= await userBusiness.signup(name, email, password);

res.status(200).send({
message: 'Usuário criado com sucesso',
token
});


} catch (e) {
res.status(400).send({
message: e.message
})
}
await BaseDatabase.destroyConnection();
};
32 changes: 32 additions & 0 deletions src/data/BaseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import knex from "knex";
import Knex from "knex";


export abstract class BaseDatabase {

private static connection: Knex | null = null;

protected getConnection(): Knex{
if(!BaseDatabase.connection){
BaseDatabase.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_NAME,
},
});
}

return BaseDatabase.connection;
}

public static async destroyConnection(): Promise<void>{
if(BaseDatabase.connection){
await BaseDatabase.connection.destroy();
BaseDatabase.connection = null;
}
}
}
26 changes: 26 additions & 0 deletions src/data/BooksRelationDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {BaseDatabase} from "./BaseDatabase";

export class BooksRelationDatabase extends BaseDatabase{
private static TABLE_NAME = 'users_relation';

public async amizadeUser(userId:string, amizadeId: string): Promise<void> {
await this.getConnection()
.insert({
user_id: userId,
fazeramizade: amizadeId
}).into(BooksRelationDatabase.TABLE_NAME)
}




public async unFollowUser(userId:string, userToUnFollowId: string): Promise<void> {
await this.getConnection()
.del()
.from(BooksRelationDatabase.TABLE_NAME)
.where({
user_id: userId,
fazeramizade: userToUnFollowId
});
}
}
Loading