Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
.env
build
2 changes: 0 additions & 2 deletions README.md

This file was deleted.

2,986 changes: 2,986 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

43 changes: 43 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "turing-labook8",
"version": "1.0.0",
"description": "Repositório do projeto Labook",
"main": "index.js",
"scripts": {
"start:dev": "ts-node-dev ./src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/future4code/turing-labook8.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/future4code/turing-labook8/issues"
},
"homepage": "https://github.com/future4code/turing-labook8#readme",
"dependencies": {
"@types/bcrypt": "^3.0.0",
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.0",
"@types/jsonwebtoken": "^8.5.0",
"@types/knex": "^0.16.1",
"@types/node": "^14.11.2",
"@types/uuid": "^8.3.0",
"bcrypt": "^5.0.0",
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.0",
"jsonwebtoken": "^8.5.1",
"knex": "^0.21.5",
"moment": "^2.29.0",
"mysql": "^2.18.1",
"typescript": "^4.0.2",
"uuid": "^8.3.0"
},
"devDependencies": {
"ts-node-dev": "^1.0.0-pre.63"
}
}
124 changes: 124 additions & 0 deletions src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { IdGenerator } from "../services/IdGenerator";
import { HashManager } from "../services/HashManager";
import { UserDatabase } from "../data/UserDatabase";
import { Authenticator } from "../services/Authenticator";
import { UserRelationDatabase } from "../data/UserRelationDatabase";
import { FeedDatabase } from "../data/FeedDatabase";

export class UserBusiness {

public async signUp(name: string, email: string, password: string): Promise<string> {

if (!name || !email || !password) {
throw new Error('Insira todas as informações necessárias para o cadastro');
}

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

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

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

const userDataBase = new UserDatabase();
await userDataBase.registerUser(
id,
name,
email,
hashPassword
);

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

return token;
}


public async makeFriend(token: string, makeFriendshipUserId: string): Promise<void> {

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

if(!makeFriendshipUserId){
throw new Error("Insira um ID válido")
}

const userDatabase = new UserDatabase();
const user = await userDatabase.getUserById(makeFriendshipUserId)

if(!user){
throw new Error("Usuário não existe")
}
Copy link
Author

Choose a reason for hiding this comment

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

Excelente verificação!


const userRelationDatabase = new UserRelationDatabase();
await userRelationDatabase.makeFriend(userId, makeFriendshipUserId)
await userRelationDatabase.makeFriend(makeFriendshipUserId, userId)

}

public async undoFriend(token: string, undoFriendshipUserId: string): Promise<void> {

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

if(!undoFriendshipUserId){
throw new Error("Insira um ID válido")
}

const userDatabase = new UserDatabase();
const user = await userDatabase.getUserById(undoFriendshipUserId)

if(!user){
throw new Error("Usuário não existe")
}

const userRelationDatabase = new UserRelationDatabase();
await userRelationDatabase.undoFriend(userId, undoFriendshipUserId)
await userRelationDatabase.undoFriend(undoFriendshipUserId, userId)
Copy link
Author

Choose a reason for hiding this comment

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

Ficou repetido aqui! rs

Ahhh, uma coisa legal de fazer, tanto na hora de fazer amizade, quanto na hora de desfazer, é verificar se já existe amizade entre os dois usuários!

}
async getUserByEmail(user:any) {

const userDatabase = new UserDatabase();
const userFromDB = await userDatabase.getUserByEmail(user.email);

if (userFromDB === undefined) {
throw new Error('Email ou senha incorretos');
}

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

const authenticator = new Authenticator();
const accessToken = authenticator.generateToken({ id: userFromDB.id });


if (!hashCompare) {
throw new Error("Email ou senha incorretos");
}

return accessToken;

}

async get(token:string){
Copy link
Author

Choose a reason for hiding this comment

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

O médoto com o nome apenas get no UserBusiness me faz pensar que é um método para pegar o usuário e não o feed! Vale ser um pouquinho mais específico aqui :)

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)=>({
title: item.title,
photoPost: item.photoPost,
description: item.description
}))

return mappedFeed
}
}
27 changes: 27 additions & 0 deletions src/data/BaseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import knex from 'knex';
import Knex from 'knex';

export abstract class BaseDatabase {
private static connection: Knex | null = null;
protected getConnection(): Knex {
if(BaseDatabase.connection === null) {
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
}
})
}
return BaseDatabase.connection;
}
public static async destroyConnection(): Promise<void> {
if(BaseDatabase.connection) {
await BaseDatabase.connection.destroy();
BaseDatabase.connection = null;
}
}
}
16 changes: 16 additions & 0 deletions src/data/FeedDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {BaseDatabase} from "./BaseDatabase";

export class FeedDatabase extends BaseDatabase{
public async getFeed(userId: string): Promise<any>{
const result = await this.getConnection().raw(`
SELECT title, photoPost, description
FROM Posts
JOIN user_relation
ON user_relation.user_id = Posts.user_id
AND user_relation.user_id = '${userId}'
JOIN users
ON Posts.user_id = users.id
`)
return result[0]
}
}
68 changes: 68 additions & 0 deletions src/data/PostDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { BaseDatabase } from "./BaseDatabase";
import { Post, PostAndUserNameOutputDTO } from "../model/Post";
import { POST_TYPE } from '../model/Post'

export class PostDatabase extends BaseDatabase {
private static TABLE_NAME = 'Posts';

public async createPost(post_id: string, user_id: string, title: string, photoPost: string, typePost: POST_TYPE, description: string, createdAt: string): Promise<void> {
await this.getConnection()
.insert({
post_id,
user_id,
title,
photoPost,
typePost,
description,
createdAt
}).into(PostDatabase.TABLE_NAME)
}

public async getPostById(postId: string): Promise<Post> {
const result = await this.getConnection()
.select('*')
.from(PostDatabase.TABLE_NAME)
.where({ post_id: postId });

return Post.toPostModel(result[0]);
}

public async getPostByUserId(userId: string): Promise<Post[]> {
const result = await this.getConnection()
.select('*')
.from(PostDatabase.TABLE_NAME)
.where({ user_id: userId });

const posts: Post[] = [];

for (let post of result) {
posts.push(Post.toPostModel(post));
Copy link
Author

Choose a reason for hiding this comment

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

Show!!!

}

return posts;
}

public async getPostInfoAndUserName(): Promise<PostAndUserNameOutputDTO[]> {

const result = await this.getConnection().raw(`
select r.*, u.name from Posts r
JOIN Users u
ON r.user_id = u.id;
`);

const posts: PostAndUserNameOutputDTO[] = [];
for(let post of result[0]){
posts.push({
id: post.post_id,
userId: post.user_id,
title: post.title,
photoPost: post.photoPost,
typePost: post.typePost,
description: post.description,
createdAt: post.createdAt,
userName: post.name});
}

return posts;
}
}
48 changes: 48 additions & 0 deletions src/data/UserDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {BaseDatabase} from "./BaseDatabase";
import { User } from "../model/User";

export class UserDatabase extends BaseDatabase {
private static TABLE_NAME: string = 'users';

public async registerUser(id: string, name: string, email: string, password: string): Promise<void> {
await this.getConnection()
.insert({
id,
name,
email,
password
}).into(UserDatabase.TABLE_NAME);
}

public async getUserByEmail(email: string): Promise<any> {
const result = await this.getConnection()
.select('*')
.from(UserDatabase.TABLE_NAME)
.where({ email});
return result[0]
}

public async getUserById(id: string): Promise<User> {
const result = await this.getConnection()
.select('*')
.from(UserDatabase.TABLE_NAME)
.where({ id });

return User.toUserModel(result[0]);
}

public async get(): Promise<any[]> {
try {
const users: any = [];
const result = await this.getConnection()
.select("*")
.from(UserDatabase.TABLE_NAME);
for(let user of result){
users.push(user);
}
return users;
} catch (error) {
throw new Error(error.sqlMessage || error.message);
}
}
}
23 changes: 23 additions & 0 deletions src/data/UserRelationDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { BaseDatabase } from "./BaseDatabase"

export class UserRelationDatabase extends BaseDatabase {
private static TABLE_NAME = 'user_relation'

public async makeFriend (userId: string, makeFriendshipUserId: string): Promise<void>{
await this.getConnection()
.insert({
user_id: userId,
user_to_be_friend: makeFriendshipUserId
}).into(UserRelationDatabase.TABLE_NAME)
}

public async undoFriend (userId: string, undoFriendshipUserId: string): Promise<void>{
await this.getConnection()
.delete()
.from(UserRelationDatabase.TABLE_NAME)
.where({
user_id: userId,
user_to_be_friend: undoFriendshipUserId
})
}
}
Loading
Loading