Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feito os dois primeiros #57

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
4 changes: 4 additions & 0 deletions Semana18/Aula1/Exercicios/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
build
.env
.vscode
2,649 changes: 2,649 additions & 0 deletions Semana18/Aula1/Exercicios/package-lock.json

Large diffs are not rendered by default.

35 changes: 35 additions & 0 deletions Semana18/Aula1/Exercicios/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "to-do-list",
"version": "1.0.0",
"description": "## ESTRUTURA DE DADOS",
"main": "index.js",
"scripts": {
"start": "tsc && node --inspect ./build/index.js",
"dev": "ts-node-dev ./src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"knex": "^0.21.5",
"mysql": "^2.18.1",
"uuid": "^8.3.1"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.8",
"@types/express": "^4.17.8",
"@types/jsonwebtoken": "^8.5.0",
"@types/knex": "^0.16.1",
"@types/node": "^14.11.2",
"@types/uuid": "^8.3.0",
"ts-node-dev": "^1.0.0-pre.63",
"typescript": "^4.0.3"
}
}
Binary file added Semana18/Aula1/Exercicios/src/.DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions Semana18/Aula1/Exercicios/src/Business/getBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@


export const getBusiness = async (input: ) => {

}
36 changes: 36 additions & 0 deletions Semana18/Aula1/Exercicios/src/Business/loginBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { selectUserByEmail } from "../data/selectUserByEmail";
import { generateToken } from "../services/authenticator";
import { compare } from "../services/hashManager";
import { loginInput, user } from "../types/user";

export const loginBusiness = async (input: loginInput): Promise<string> => {
try {
if (!input.email || !input.password) {
throw new Error("'email' e 'senha' são obrigatórios")
}

const user: user = await selectUserByEmail(input.email)

if (!user) {
throw new Error("Usuário não encontrado ou senha incorreta")
}

const passwordIsCorrect: boolean = await compare(input.password, user.password)

if (!passwordIsCorrect) {
throw new Error("Usuário não encontrado ou senha incorreta")
}

const token: string = generateToken({
id: user.id,
role: user.role
})

return token;

} catch (error) {
throw new Error(error.message)
}


}
45 changes: 45 additions & 0 deletions Semana18/Aula1/Exercicios/src/Business/signupBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { insertUser } from "../data/insertUser";
import { generateToken } from "../services/authenticator";
import { hash } from "../services/hashManager";
import { generateId } from "../services/idGenerator";
import { convertStringToUserRole, signupInput } from "../types/user";

export const signupBusiness = async (input: signupInput): Promise<string> => {
try {
if(
!input.name ||
!input.nickname ||
!input.email ||
!input.password ||
!input.role
) {
throw new Error ('invalid fields: "name", "nickname", "email", "password" or "role"' )
}

const id: string = generateId()

const hashedPassword = await hash(input.password)

await insertUser({
id,
name: input.name,
nickname: input.nickname,
email: input.email,
password: hashedPassword,
role: convertStringToUserRole(input.role)

})

const token: string = generateToken({
id,
role: convertStringToUserRole(input.role)
})

return token


} catch (error) {
throw new Error(error.message)
}

}
20 changes: 20 additions & 0 deletions Semana18/Aula1/Exercicios/src/Controller/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

import {Request, Response} from "express"
import { getBusiness } from "../Business/getBusiness";


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


try {

const token = req.headers.authorization!;

const users = await getBusiness(token);

res.send(users).status(200);

} catch (error) {
res.send({ message: error.message }).status(error.status);
}
}
26 changes: 26 additions & 0 deletions Semana18/Aula1/Exercicios/src/Controller/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {Request, Response} from 'express'
import { loginBusiness } from '../Business/loginBusiness';
import { loginInput } from '../types/user';

export const login = async (
req: Request,
res: Response
): Promise<void> => {
try {


const { email, password } = req.body as loginInput;


const token: string = await loginBusiness({ email, password });


res.send({
message: "Welcome!!",
token
})

} catch (error) {
res.status(400).send(error.message)
}
}
29 changes: 29 additions & 0 deletions Semana18/Aula1/Exercicios/src/Controller/signup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Request, Response } from "express";
import { signupBusiness } from "../Business/signupBusiness";
import { signupInput } from "../types/user";

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

//é responsabilidade da controller. Está capturando os valores da
//requisição
const { name, nickname, email, password, role } = req.body as signupInput;

//receber os valores que precisam ser enviados na resposta
const token = await signupBusiness({ name, nickname, email, password, role });

//enviar a resposta
res
.status(201)
.send({
message: "Usuário criado!",
token
})

} catch (error) {
res.status(400).send(error.message)
}
}
22 changes: 22 additions & 0 deletions Semana18/Aula1/Exercicios/src/data/getData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { connection } from "..";

export const getData = async(): Promise<any[]> => {

try {

const users: any = [];

const result = await connection()
.select("*")
.from(TABLE_NAME);

for(let user of result){
users.push(user);
}

return users;

} catch (error) {
throw new Error(error.sqlMessage || error.message);
}
}
15 changes: 15 additions & 0 deletions Semana18/Aula1/Exercicios/src/data/insertTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { connection } from "..";
import { task } from "../types/task";

export const insertTask = async (
task: task
) => {
await connection('to_do_list_tasks')
.insert({
id: task.id,
title: task.title,
description: task.description,
deadline: task.deadline,
author_id: task.authorId
})
}
15 changes: 15 additions & 0 deletions Semana18/Aula1/Exercicios/src/data/insertUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { connection } from "../index";
import { user } from "../types/user";

export const insertUser = async(
user: user
) => {
await connection.insert({
id: user.id,
name: user.name,
nickname: user.nickname,
email: user.email,
password: user.password,
role: user.role
}).into('to_do_list_users')
}
14 changes: 14 additions & 0 deletions Semana18/Aula1/Exercicios/src/data/selectTaskById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { connection } from "..";

export const selectTaskById = async (
id: string
): Promise<any> => {
const result = await connection.raw(`
SELECT tasks.*, nickname FROM to_do_list_tasks AS tasks
JOIN to_do_list_users AS users
ON author_id = users.id
WHERE tasks.id = '${id}';
`)

return result[0][0]
}
24 changes: 24 additions & 0 deletions Semana18/Aula1/Exercicios/src/data/selectUserByEmail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { connection } from ".."
import { user } from "../types/user"

export const selectUserByEmail = async (
email: string
): Promise<user> => {
try {
const result = await connection("to_do_list_users")
.select("*")
.where({ email })

return {
id: result[0].id,
name: result[0].name,
nickname: result[0].nickname,
email: result[0].email,
password: result[0].password,
role: result[0].role
}

} catch (error) {
throw new Error(error.slqMessage || error.message)
}
}
39 changes: 39 additions & 0 deletions Semana18/Aula1/Exercicios/src/endpoints/createTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Request, Response } from "express";
import {insertTask} from "../data/insertTask";
import { generateId } from "../services/idGenerator";

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

const { title, description, deadline, authorId } = req.body

if (
!title ||
!description ||
!deadline ||
!authorId
) {
throw new Error('"title", "description", "deadline" e "authorId" são obrigatórios')
}

const id: string = generateId()

await insertTask({
id,
title,
description,
deadline,
authorId,
})

res.status(201).end()

} catch (error) {

res.statusMessage = error.message
res.status(500).end()
}
}
33 changes: 33 additions & 0 deletions Semana18/Aula1/Exercicios/src/endpoints/getTaskById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Request, Response } from "express";
import {selectTaskById} from "../data/selectTaskById";

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

const { id } = req.params

const result = await selectTaskById(id)

if (!result) {
throw new Error("Tarefa não encontrada")
}

const taskWithUserInfo = {
id: result.id,
title: result.title,
description: result.description,
deadline: result.deadline,
status: result.status,
authorId: result.author_id,
authorNickname: result.nickname
}

res.status(200).send(taskWithUserInfo)

} catch (error) {
res.status(400).send(error.message)
}
}
Loading