Skip to content

Commit

Permalink
Merge pull request #2 from mibrito1/users
Browse files Browse the repository at this point in the history
comecei o business
  • Loading branch information
mibrito1 authored Sep 26, 2023
2 parents bc66094 + a0f4f4e commit aec4a4f
Show file tree
Hide file tree
Showing 11 changed files with 1,409 additions and 26 deletions.
1,249 changes: 1,227 additions & 22 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@types/cors": "^2.8.14",
"@types/express": "^4.17.18",
"@types/jsonwebtoken": "^9.0.3",
"@types/knex": "^0.16.1",
"@types/node": "^20.6.5",
"@types/uuid": "^9.0.4",
"ts-node-dev": "^2.0.0",
Expand All @@ -26,6 +27,9 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"uuid": "^9.0.1"
"knex": "^2.5.1",
"sqlite3": "^5.1.6",
"uuid": "^9.0.1",
"zod": "^3.22.2"
}
}
49 changes: 49 additions & 0 deletions src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { error } from "console";
import { UserDataBase } from "../dataBase/UserDataBase";
import { SignupInputDTO, SignupOutputDTO } from "../dtos/users/signup.dto";
import { IdGenerator } from "../services/IdGenerator";
import { HashManager } from "../services/HashManager";
import { Users, userRole } from "../models/Users";
import { TokenManager, TokenPayload } from "../services/TokenManager";

export class UserBusiness { // aqui vai tratar as regras do negocio, as regras do projeto
constructor(private idGenerator: IdGenerator,
private userDataBase: UserDataBase,
private hashManager: HashManager,
private tokenManager: TokenManager
) {

}
public signup = async (input: SignupInputDTO): Promise<SignupOutputDTO> => {
const {
name, email, password
} = input
const id = this.idGenerator.generate()
const userExist = await this.userDataBase.getUserByEmail(email)
if (
userExist
) {
throw new Error(
"usuario ja existe"
)
}
const passwordSec = await this.hashManager.hash(password)
const user = new Users(id, name, email, passwordSec, userRole.Normal, new Date().toISOString())
await this.userDataBase.signup(user.toUserDb())
const tokenPayload: TokenPayload = {
id: user.getId(),
name: user.getName(),
role: user.getRole()
}
const token = this.tokenManager.createToken(tokenPayload)
const output: SignupOutputDTO = {
message: "usuario registrado com sucesso",
token: token


}
return output
}

}

33 changes: 31 additions & 2 deletions src/controller/UserController.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
import { Request, Response } from "express";
import { UserBusiness } from "../business/UserBusiness";
import { SignupSchema } from "../dtos/users/signup.dto";
import { ZodError } from "zod";
import { BaseError } from "../erros/BaseError";


export class UserController {
constructor() { }
constructor(
private userBusiness: UserBusiness
) { }
public oiMirian = async (req: Request, res: Response) => {
res.send("Oi, Chegou a Mirian")
}
}
public signup = async (req: Request, res: Response) => {
try {
const input = SignupSchema.parse({
name: req.body.name,
email: req.body.email,
password: req.body.password
})
const output = await this.userBusiness.signup(input)
res.status(201).send(output)

} catch (error) {
console.log(error)
if (error instanceof ZodError) {
res.status(400).send(error.issues)
} else if (error instanceof BaseError) {
res.status(error.statusCode).send(error.message)
} else {
res.status(500).send("Erro inesperado")
}

}
}
}
18 changes: 18 additions & 0 deletions src/dataBase/BaseDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import knex from "knex"

export abstract class BaseDatabase {
protected static connection = knex({
client: "sqlite3",
connection: {
filename: "./labook.db"
},
useNullAsDefault: true,
pool: {
min: 0,
max: 1,
afterCreate: (conn: any, cb: any) => {
conn.run("PRAGMA foreign_keys = ON", cb)
}
}
})
}
20 changes: 20 additions & 0 deletions src/dataBase/UserDataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { promises } from "dns";
import { UserDb } from "../models/Users";
import { BaseDatabase } from "./BaseDataBase";

export class UserDataBase extends BaseDatabase {
public static USERS_TABLE = "users"
public async signup(
user: UserDb
) {
await BaseDatabase.connection(UserDataBase.USERS_TABLE).insert(user)

}
public async getUserByEmail(email: string): Promise<UserDb> {
const [response]: UserDb[] = await BaseDatabase.connection(UserDataBase.USERS_TABLE).where({
email
})
return response
}

}
2 changes: 2 additions & 0 deletions src/dataBase/labook.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ CREATE TABLE
created_at TEXT NOT NULL
);

DROP TABLE users;

SELECT * FROM users;
17 changes: 17 additions & 0 deletions src/dtos/users/login.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import z from "zod"

export interface LoginInputDTO {
email: string,
password: String // aqui tipei a entrada de dados
}

export interface LoginOutputDTO {
message: string,
token: string // tipando o retorno
}

export const LoginSchema = z.object({
email: z.string().email(),
password: z.string().min(6)
}).transform((data) => data as LoginInputDTO)

16 changes: 16 additions & 0 deletions src/dtos/users/signup.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import z from "zod"

export interface SignupInputDTO {
email: string,
password: string,
name: string
}
export interface SignupOutputDTO {
message: string,
token: string
}
export const SignupSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
password: z.string().min(6)
}).transform((data) => data as SignupInputDTO)
9 changes: 9 additions & 0 deletions src/erros/BaseError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export abstract class BaseError extends Error { // criando classe para ser reutilizada ( abstract) e erda as caracteristicas do erro

constructor(
public statusCode: number,
message: string) {
super(message)
}

}
16 changes: 15 additions & 1 deletion src/router/userRouter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
import express, { Request, Response } from "express";
import { UserController } from "../controller/UserController";
import { UserBusiness } from "../business/UserBusiness";
import { IdGenerator } from "../services/IdGenerator";
import { UserDataBase } from "../dataBase/UserDataBase";
import { HashManager } from "../services/HashManager";
import { TokenManager } from "../services/TokenManager";


export const userRouter = express.Router()
const userController = new UserController() //instancia
const userController = new UserController(
new UserBusiness(
new IdGenerator(),
new UserDataBase(),
new HashManager(),
new TokenManager()
)
) //instancia
userRouter.get("/", userController.oiMirian)

userRouter.post('/signup', userController.signup)

0 comments on commit aec4a4f

Please sign in to comment.