Skip to content

Commit 7a88b86

Browse files
Merge pull request #9 from future4code/master
Correção do Projeto
2 parents 372e6ae + a778f73 commit 7a88b86

25 files changed

Lines changed: 3734 additions & 2 deletions

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules
2+
.env
3+
build

README.md

Lines changed: 0 additions & 2 deletions
This file was deleted.

package-lock.json

Lines changed: 2986 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"name": "turing-labook8",
3+
"version": "1.0.0",
4+
"description": "Repositório do projeto Labook",
5+
"main": "index.js",
6+
"scripts": {
7+
"start:dev": "ts-node-dev ./src/index.ts",
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
},
10+
"repository": {
11+
"type": "git",
12+
"url": "git+https://github.com/future4code/turing-labook8.git"
13+
},
14+
"keywords": [],
15+
"author": "",
16+
"license": "ISC",
17+
"bugs": {
18+
"url": "https://github.com/future4code/turing-labook8/issues"
19+
},
20+
"homepage": "https://github.com/future4code/turing-labook8#readme",
21+
"dependencies": {
22+
"@types/bcrypt": "^3.0.0",
23+
"@types/bcryptjs": "^2.4.2",
24+
"@types/express": "^4.17.0",
25+
"@types/jsonwebtoken": "^8.5.0",
26+
"@types/knex": "^0.16.1",
27+
"@types/node": "^14.11.2",
28+
"@types/uuid": "^8.3.0",
29+
"bcrypt": "^5.0.0",
30+
"bcryptjs": "^2.4.3",
31+
"dotenv": "^8.2.0",
32+
"express": "^4.17.0",
33+
"jsonwebtoken": "^8.5.1",
34+
"knex": "^0.21.5",
35+
"moment": "^2.29.0",
36+
"mysql": "^2.18.1",
37+
"typescript": "^4.0.2",
38+
"uuid": "^8.3.0"
39+
},
40+
"devDependencies": {
41+
"ts-node-dev": "^1.0.0-pre.63"
42+
}
43+
}

src/business/UserBusiness.ts

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { IdGenerator } from "../services/IdGenerator";
2+
import { HashManager } from "../services/HashManager";
3+
import { UserDatabase } from "../data/UserDatabase";
4+
import { Authenticator } from "../services/Authenticator";
5+
import { UserRelationDatabase } from "../data/UserRelationDatabase";
6+
import { FeedDatabase } from "../data/FeedDatabase";
7+
8+
export class UserBusiness {
9+
10+
public async signUp(name: string, email: string, password: string): Promise<string> {
11+
12+
if (!name || !email || !password) {
13+
throw new Error('Insira todas as informações necessárias para o cadastro');
14+
}
15+
16+
if (password.length < 6) {
17+
throw new Error('A senha deve conter no mínimo seis caracteres');
18+
}
19+
20+
const idGenerator = new IdGenerator();
21+
const id = idGenerator.generateId();
22+
23+
const hashManager = new HashManager();
24+
const hashPassword = await hashManager.hash(password);
25+
26+
const userDataBase = new UserDatabase();
27+
await userDataBase.registerUser(
28+
id,
29+
name,
30+
email,
31+
hashPassword
32+
);
33+
34+
const authenticator = new Authenticator();
35+
const token = authenticator.generateToken({ id });
36+
37+
return token;
38+
}
39+
40+
41+
public async makeFriend(token: string, makeFriendshipUserId: string): Promise<void> {
42+
43+
const authenticator = new Authenticator;
44+
const authenticationData = authenticator.verify(token)
45+
const userId = authenticationData.id
46+
47+
if(!makeFriendshipUserId){
48+
throw new Error("Insira um ID válido")
49+
}
50+
51+
const userDatabase = new UserDatabase();
52+
const user = await userDatabase.getUserById(makeFriendshipUserId)
53+
54+
if(!user){
55+
throw new Error("Usuário não existe")
56+
}
57+
58+
const userRelationDatabase = new UserRelationDatabase();
59+
await userRelationDatabase.makeFriend(userId, makeFriendshipUserId)
60+
await userRelationDatabase.makeFriend(makeFriendshipUserId, userId)
61+
62+
}
63+
64+
public async undoFriend(token: string, undoFriendshipUserId: string): Promise<void> {
65+
66+
const authenticator = new Authenticator;
67+
const authenticationData = authenticator.verify(token)
68+
const userId = authenticationData.id
69+
70+
if(!undoFriendshipUserId){
71+
throw new Error("Insira um ID válido")
72+
}
73+
74+
const userDatabase = new UserDatabase();
75+
const user = await userDatabase.getUserById(undoFriendshipUserId)
76+
77+
if(!user){
78+
throw new Error("Usuário não existe")
79+
}
80+
81+
const userRelationDatabase = new UserRelationDatabase();
82+
await userRelationDatabase.undoFriend(userId, undoFriendshipUserId)
83+
await userRelationDatabase.undoFriend(undoFriendshipUserId, userId)
84+
}
85+
async getUserByEmail(user:any) {
86+
87+
const userDatabase = new UserDatabase();
88+
const userFromDB = await userDatabase.getUserByEmail(user.email);
89+
90+
if (userFromDB === undefined) {
91+
throw new Error('Email ou senha incorretos');
92+
}
93+
94+
const hashManager = new HashManager();
95+
const hashCompare = await hashManager.compare(user.password, userFromDB.password);
96+
97+
const authenticator = new Authenticator();
98+
const accessToken = authenticator.generateToken({ id: userFromDB.id });
99+
100+
101+
if (!hashCompare) {
102+
throw new Error("Email ou senha incorretos");
103+
}
104+
105+
return accessToken;
106+
107+
}
108+
109+
async get(token:string){
110+
const authenticator = new Authenticator();
111+
const authenticationData = authenticator.verify(token);
112+
const userId = authenticationData.id;
113+
114+
const feedDatabase = new FeedDatabase();
115+
const feed = await feedDatabase.getFeed(userId);
116+
const mappedFeed = feed.map((item:any)=>({
117+
title: item.title,
118+
photoPost: item.photoPost,
119+
description: item.description
120+
}))
121+
122+
return mappedFeed
123+
}
124+
}

src/data/BaseDatabase.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import knex from 'knex';
2+
import Knex from 'knex';
3+
4+
export abstract class BaseDatabase {
5+
private static connection: Knex | null = null;
6+
protected getConnection(): Knex {
7+
if(BaseDatabase.connection === null) {
8+
BaseDatabase.connection = knex({
9+
client: "mysql",
10+
connection: {
11+
host: process.env.DB_HOST,
12+
port: 3306,
13+
user: process.env.DB_USER,
14+
password: process.env.DB_PASSWORD,
15+
database: process.env.DB_DATABASE
16+
}
17+
})
18+
}
19+
return BaseDatabase.connection;
20+
}
21+
public static async destroyConnection(): Promise<void> {
22+
if(BaseDatabase.connection) {
23+
await BaseDatabase.connection.destroy();
24+
BaseDatabase.connection = null;
25+
}
26+
}
27+
}

src/data/FeedDatabase.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import {BaseDatabase} from "./BaseDatabase";
2+
3+
export class FeedDatabase extends BaseDatabase{
4+
public async getFeed(userId: string): Promise<any>{
5+
const result = await this.getConnection().raw(`
6+
SELECT title, photoPost, description
7+
FROM Posts
8+
JOIN user_relation
9+
ON user_relation.user_id = Posts.user_id
10+
AND user_relation.user_id = '${userId}'
11+
JOIN users
12+
ON Posts.user_id = users.id
13+
`)
14+
return result[0]
15+
}
16+
}

src/data/PostDatabase.ts

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { BaseDatabase } from "./BaseDatabase";
2+
import { Post, PostAndUserNameOutputDTO } from "../model/Post";
3+
import { POST_TYPE } from '../model/Post'
4+
5+
export class PostDatabase extends BaseDatabase {
6+
private static TABLE_NAME = 'Posts';
7+
8+
public async createPost(post_id: string, user_id: string, title: string, photoPost: string, typePost: POST_TYPE, description: string, createdAt: string): Promise<void> {
9+
await this.getConnection()
10+
.insert({
11+
post_id,
12+
user_id,
13+
title,
14+
photoPost,
15+
typePost,
16+
description,
17+
createdAt
18+
}).into(PostDatabase.TABLE_NAME)
19+
}
20+
21+
public async getPostById(postId: string): Promise<Post> {
22+
const result = await this.getConnection()
23+
.select('*')
24+
.from(PostDatabase.TABLE_NAME)
25+
.where({ post_id: postId });
26+
27+
return Post.toPostModel(result[0]);
28+
}
29+
30+
public async getPostByUserId(userId: string): Promise<Post[]> {
31+
const result = await this.getConnection()
32+
.select('*')
33+
.from(PostDatabase.TABLE_NAME)
34+
.where({ user_id: userId });
35+
36+
const posts: Post[] = [];
37+
38+
for (let post of result) {
39+
posts.push(Post.toPostModel(post));
40+
}
41+
42+
return posts;
43+
}
44+
45+
public async getPostInfoAndUserName(): Promise<PostAndUserNameOutputDTO[]> {
46+
47+
const result = await this.getConnection().raw(`
48+
select r.*, u.name from Posts r
49+
JOIN Users u
50+
ON r.user_id = u.id;
51+
`);
52+
53+
const posts: PostAndUserNameOutputDTO[] = [];
54+
for(let post of result[0]){
55+
posts.push({
56+
id: post.post_id,
57+
userId: post.user_id,
58+
title: post.title,
59+
photoPost: post.photoPost,
60+
typePost: post.typePost,
61+
description: post.description,
62+
createdAt: post.createdAt,
63+
userName: post.name});
64+
}
65+
66+
return posts;
67+
}
68+
}

src/data/UserDatabase.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import {BaseDatabase} from "./BaseDatabase";
2+
import { User } from "../model/User";
3+
4+
export class UserDatabase extends BaseDatabase {
5+
private static TABLE_NAME: string = 'users';
6+
7+
public async registerUser(id: string, name: string, email: string, password: string): Promise<void> {
8+
await this.getConnection()
9+
.insert({
10+
id,
11+
name,
12+
email,
13+
password
14+
}).into(UserDatabase.TABLE_NAME);
15+
}
16+
17+
public async getUserByEmail(email: string): Promise<any> {
18+
const result = await this.getConnection()
19+
.select('*')
20+
.from(UserDatabase.TABLE_NAME)
21+
.where({ email});
22+
return result[0]
23+
}
24+
25+
public async getUserById(id: string): Promise<User> {
26+
const result = await this.getConnection()
27+
.select('*')
28+
.from(UserDatabase.TABLE_NAME)
29+
.where({ id });
30+
31+
return User.toUserModel(result[0]);
32+
}
33+
34+
public async get(): Promise<any[]> {
35+
try {
36+
const users: any = [];
37+
const result = await this.getConnection()
38+
.select("*")
39+
.from(UserDatabase.TABLE_NAME);
40+
for(let user of result){
41+
users.push(user);
42+
}
43+
return users;
44+
} catch (error) {
45+
throw new Error(error.sqlMessage || error.message);
46+
}
47+
}
48+
}

src/data/UserRelationDatabase.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { BaseDatabase } from "./BaseDatabase"
2+
3+
export class UserRelationDatabase extends BaseDatabase {
4+
private static TABLE_NAME = 'user_relation'
5+
6+
public async makeFriend (userId: string, makeFriendshipUserId: string): Promise<void>{
7+
await this.getConnection()
8+
.insert({
9+
user_id: userId,
10+
user_to_be_friend: makeFriendshipUserId
11+
}).into(UserRelationDatabase.TABLE_NAME)
12+
}
13+
14+
public async undoFriend (userId: string, undoFriendshipUserId: string): Promise<void>{
15+
await this.getConnection()
16+
.delete()
17+
.from(UserRelationDatabase.TABLE_NAME)
18+
.where({
19+
user_id: userId,
20+
user_to_be_friend: undoFriendshipUserId
21+
})
22+
}
23+
}

0 commit comments

Comments
 (0)