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 semana19/aula-65-testes/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.env
testeAnagrama
8 changes: 8 additions & 0 deletions semana19/aula-65-testes/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
roots: ["<rootDir>/tests"],
transform: {
"^.+\\.tsx?$": "ts-jest",
},
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};
6,887 changes: 6,887 additions & 0 deletions semana19/aula-65-testes/package-lock.json

Large diffs are not rendered by default.

35 changes: 35 additions & 0 deletions semana19/aula-65-testes/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "sagan-ordenacao",
"version": "1.0.0",
"description": "Paginação, ordenação e filtros",
"main": "index.js",
"scripts": {
"test": "jest",
"start": "ts-node ./src/index.ts",
"start:dev": " ts-node-dev ./src/index.ts",
"check": "ts-node ./testeAnagrama.ts"
},
"author": "João Golias",
"license": "ISC",
"dependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.6",
"@types/jest": "^25.2.3",
"@types/jsonwebtoken": "^8.5.0",
"@types/knex": "^0.16.1",
"@types/uuid": "^7.0.3",
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jest": "^26.0.1",
"jsonwebtoken": "^8.5.1",
"knex": "^0.21.1",
"mysql": "^2.18.1",
"ts-jest": "^26.1.0",
"typescript": "^3.9.2",
"uuid": "^8.0.0"
},
"devDependencies": {
"ts-node-dev": "^1.0.0-pre.44"
}
}
Binary file added semana19/aula-65-testes/src/.DS_Store
Binary file not shown.
92 changes: 92 additions & 0 deletions semana19/aula-65-testes/src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { UserDatabase } from './../data/UserDatabase';
import { User, stringToUserRole } from "../model/User";
import { IdGenerator } from "../services/idGenerator";
import { HashGenerator } from "../services/hashGenerator";
import { TokenGenerator } from "../services/tokenGenerator";
import { NotFoundError } from "../errors/NotFoundError";
import { InvalidParameterError } from "../errors/InvalidParameterError";
export class UserBusiness {

constructor(
private userDatabase: UserDatabase,
private idGenerator: IdGenerator,
private hashGenerator: HashGenerator,
private tokenGenerator: TokenGenerator
) { }

public async signup(
name: string,
email: string,
password: string,
role: string
) {

if (!name || !email || !password || !role) {
throw new InvalidParameterError("Missing input");
}

if (email.indexOf("@") === -1) {
throw new InvalidParameterError("Invalid email");
}

if (password.length < 6) {
throw new InvalidParameterError("Invalid password");
}

const id = this.idGenerator.generate();

const cryptedPassword = await this.hashGenerator.hash(password);

await this.userDatabase.createUser(
new User(id, name, email, cryptedPassword, stringToUserRole(role))
);

const accessToken = this.tokenGenerator.generate({
id,
role,
});
return { accessToken };
}

public async login(email: string, password: string) {
if (!email || !password) {
throw new InvalidParameterError("Missing input");
}


const user = await this.userDatabase.getUserByEmail(email);

if (!user) {
throw new NotFoundError("User not found");
}

const isPasswordCorrect = await this.hashGenerator.compareHash(
password,
user.getPassword()
);

if (!isPasswordCorrect) {
throw new InvalidParameterError("Invalid password");
}

const accessToken = this.tokenGenerator.generate({
id: user.getId(),
role: user.getRole(),
});

return { accessToken };
}

public async getUserById(id: string) {
if (!id) {
throw new NotFoundError("User not found")
}
const response = await this.userDatabase.getUserById(id);

if (!response) {
throw new NotFoundError("User not found")
}

return response;
}
}
50 changes: 50 additions & 0 deletions semana19/aula-65-testes/src/controller/UserController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Request, Response } from "express";
import { UserBusiness } from "../business/UserBusiness";
import { TokenGenerator } from "../services/tokenGenerator";
import { IdGenerator } from "../services/idGenerator";
import { UserDatabase } from "../data/UserDatabase";
import { HashGenerator } from "../services/hashGenerator";

export class UserController {

private static UserBusiness = new UserBusiness(
new UserDatabase(),
new IdGenerator(),
new HashGenerator(),
new TokenGenerator());

public async signup(req: Request, res: Response) {
try {
const result = await UserController.UserBusiness.signup(
req.body.name,
req.body.email,
req.body.password,
req.body.role
);
res.status(200).send(result);
} catch (err) {
res.status(err.errorCode || 400).send({ message: err.message });
}
}

public async login(req: Request, res: Response) {
const email = req.body.email;
const password = req.body.password;
try {
const result = await UserController.UserBusiness.login(email, password);
res.status(200).send(result);
} catch (err) {
res.status(err.errorCode || 400).send({ message: err.message });
}
}

public async getUserById(req: Request, res: Response) {
const id = req.params.id as string
try {
const result = await UserController.UserBusiness.getUserById(id)
res.status(200).send(result)
} catch (error) {
res.status(error.errorCode || 400).send({ message: error.message })
}
}
}
34 changes: 34 additions & 0 deletions semana19/aula-65-testes/src/data/BaseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import dotenv from "dotenv";
import knex from "knex";
import Knex from "knex";

dotenv.config();

export abstract class BaseDataBase {
protected abstract tableName: string;

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: Number(process.env.PORT || "3306"),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE_NAME,
},
});
}

return BaseDataBase.connection;
}

public async distroyConnection(): Promise<void> {
if (BaseDataBase.connection) {
await BaseDataBase.connection.destroy();
}
}
}
54 changes: 54 additions & 0 deletions semana19/aula-65-testes/src/data/UserDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { BaseDataBase } from "./BaseDatabase";
import { User } from "../model/User";

export class UserDatabase extends BaseDataBase {
protected tableName: string = "labook_user";

private toModel(dbModel?: any): User | undefined {
return (
dbModel &&
new User(
dbModel.id,
dbModel.name,
dbModel.email,
dbModel.password,
dbModel.role
)
);
}

public async createUser(user: User): Promise<void> {
await super.getConnection().raw(`
INSERT INTO ${this.tableName} (id, name, email, password, role)
VALUES (
'${user.getId()}',
'${user.getName()}',
'${user.getEmail()}',
'${user.getPassword()}',
'${user.getRole()}'
)`);
}

public async getUserByEmail(email: string): Promise<User | undefined> {
const result = await super.getConnection().raw(`
SELECT * from ${this.tableName} WHERE email = '${email}'
`);
return this.toModel(result[0][0]);
}

public async getUserById(id: string): Promise<User | undefined> {
const result = await super.getConnection().raw(`
SELECT * from ${this.tableName} WHERE id = '${id}'
`);
return this.toModel(result[0][0]);
}

public async getAllUsers(): Promise<User[]> {
const result = await super.getConnection().raw(`
SELECT * from ${this.tableName}
`);
return result[0].map((res: any) => {
return this.toModel(res);
});
}
}
5 changes: 5 additions & 0 deletions semana19/aula-65-testes/src/errors/BaseError/BaseError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export abstract class BaseError extends Error {
constructor(message: string, public errorCode: number) {
super(message);
}
}
7 changes: 7 additions & 0 deletions semana19/aula-65-testes/src/errors/GenericError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { BaseError } from "./BaseError/BaseError";

export class GenericError extends BaseError {
constructor(message: string) {
super(message, 400);
}
}
7 changes: 7 additions & 0 deletions semana19/aula-65-testes/src/errors/InvalidParameterError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { BaseError } from "./BaseError/BaseError";

export class InvalidParameterError extends BaseError {
constructor(message: string) {
super(message, 422);
}
}
7 changes: 7 additions & 0 deletions semana19/aula-65-testes/src/errors/NotFoundError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { BaseError } from "./BaseError/BaseError";

export class NotFoundError extends BaseError {
constructor(message: string) {
super(message, 404);
}
}
27 changes: 27 additions & 0 deletions semana19/aula-65-testes/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

import express from "express";
import { AddressInfo } from "net";
import { userRouter } from "./router/UserRouter";
const app = express();

app.use(express.json());

app.use("/users/", userRouter);


const server = app.listen(3000, () => {
if (server) {
const address = server.address() as AddressInfo;
console.log(`Servidor rodando em http://localhost:${address.port}`);
} else {
console.error(`Falha ao rodar o servidor.`);
}
});


//Faça uma função que receba duas strings e retorne true se elas forem anagramas.
//recebe duas strings
//desconstrui array
//For of


47 changes: 47 additions & 0 deletions semana19/aula-65-testes/src/model/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { InvalidParameterError } from "../errors/InvalidParameterError";

export class User {
constructor(
private id: string,
private name: string,
private email: string,
private password: string,
private role: UserRole
) {}

public getId(): string {
return this.id;
}

public getName(): string {
return this.name;
}

public getEmail(): string {
return this.email;
}

public getPassword(): string {
return this.password;
}

public getRole(): UserRole {
return this.role;
}
}

export const stringToUserRole = (input: string): UserRole => {
switch (input) {
case "NORMAL":
return UserRole.NORMAL;
case "ADMIN":
return UserRole.ADMIN;
default:
throw new InvalidParameterError("Invalid user role");
}
};

export enum UserRole {
NORMAL = "NORMAL",
ADMIN = "ADMIN",
}
8 changes: 8 additions & 0 deletions semana19/aula-65-testes/src/router/UserRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import express from "express";
import { UserController } from "../controller/UserController";
//linha responsável por criar um módulo de rotas no express
export const userRouter = express.Router();

userRouter.post("/signup", new UserController().signup);
userRouter.post("/login", new UserController().login);
userRouter.get("/profile/:id", new UserController().getUserById);
Loading