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
Binary file not shown.
4 changes: 4 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
packege-lock.json
build
.env
100 changes: 100 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# To Do List

## ESTRUTURA DE DADOS

* ## Usuários
* id
* name
* nickname
* email

* ## Tarefas
* id
* title
* description
* deadline
* status: `"to_do" || "doing" || "done"`
* author
* assignees

---

## CRIAÇÃO DE TABELAS - MySql

```sql
CREATE TABLE to_do_list_users (
id VARCHAR(64) PRIMARY KEY,
name VARCHAR(64) NOT NULL,
nickname VARCHAR(64) NOT NULL,
email VARCHAR(64) NOT NULL
);
```
```sql
CREATE TABLE to_do_list_tasks (
id VARCHAR(64) PRIMARY KEY,
title VARCHAR(64) NOT NULL,
description VARCHAR(1024) DEFAULT "No description provided",
deadline DATE,
status ENUM("TO_DO", "DOING", "DONE") DEFAULT "TO_DO",
author_id VARCHAR(64),
FOREIGN KEY (author_id) REFERENCES to_do_list_users(id)
);
```
```sql
CREATE TABLE to_do_list_assignees (
task_id VARCHAR(64),
assignee_id VARCHAR(64),
PRIMARY KEY (task_id, assignee_id),
FOREIGN KEY (task_id) REFERENCES to_do_list_tasks(id),
FOREIGN KEY (assignee_id) REFERENCES to_do_list_users(id)
);
```
---

## ENDPOINTS

* ## Criar usuário
* Método: PUT
* Path: `/user`
* Body:
* name (obrigatório)
* nickname (obrigatório)
* email (obrigatório)

* ## Pegar usuário pelo id
* Método: GET
* Path: `/user/:id`
* Body de Resposta: (retornar um erro se não encontrar)
* id
* nickname


* ## Editar usuário**
* Método: POST
* Path: `/user/edit/:id`
* Body:
* name (opcional; não pode ser vazio)
* nickname (opcional; não pode ser vazio)
* email (opcional; não pode ser vazio)


* ## Criar tarefa
* Método: PUT
* Path: `/task`
* Body:
* title (obrigatório)
* description (obrigatório)
* deadline (obrigatório; formato `YYYY-MM-DD`)
* authorId

* ## Pegar tarefa pelo id
* Método: GET
* Path: `/task/:id`
* Body de Resposta: (retornar um erro se não encontrar)
* id
* title
* description
* deadline (formato `YYYY-MM-DD`)
* status
* authorId
* authorNickname
29 changes: 29 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"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": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"knex": "^0.21.5",
"mysql": "^2.18.1"
},
"devDependencies": {
"@types/cors": "^2.8.8",
"@types/express": "^4.17.8",
"@types/knex": "^0.16.1",
"@types/node": "^14.11.2",
"ts-node-dev": "^1.0.0-pre.63",
"typescript": "^4.0.3"
}
}
18 changes: 18 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/src/data/insertTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { connection } from "..";

export default async function insertTask(
id: string,
title: string,
description: string,
deadline: string,
authorId: string
) {
await connection('to_do_list_tasks')
.insert({
id,
title,
description,
deadline,
author_id: authorId
})
}
15 changes: 15 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/src/data/insertUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { connection } from "../index";

export default async function insertUser(
id: string,
name: string,
nickname: string,
email: string
) {
await connection.insert({
id,
name,
nickname,
email
}).into('to_do_list_users')
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { connection } from "..";

export default async function selectTaskById(
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]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { connection } from "..";

export default async function selectUserById(
id: string
) {
const result = await connection('to_do_list_users')
.select('*')
.where({ id })

return result[0]
}
18 changes: 18 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/src/data/updateUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { connection } from "..";

export default async function updateUser(
id: string,
name?: string,
nickname?: string,
email?: string
) {

await connection("to_do_list_users")
.update({
name, nickname, email
})
.where({
id
})

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Request, Response } from "express";
import insertTask from "../data/insertTask";

export default async function createTask(
req: Request,
res: Response
) {
try {
if (
!req.body.title ||
!req.body.description ||
!req.body.deadline ||
!req.body.authorId
) {
throw new Error('"title", "description", "deadline" e "authorId" são obrigatórios')
}

const id: string = Date.now() + Math.random().toString()

await insertTask(
id,
req.body.title,
req.body.description,
req.body.deadline,
req.body.authorId,
)

res.status(400).send({
message: "Tarefa criada com sucesso!",
id
})

} catch (error) {
let message = error.sqlMessage || error.message

if (message.includes("date")) {
message = "'deadline' deve ser uma data válida, no formato aaaa-mm-dd"
}

res.status(400).send({ message })
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Request, Response } from "express";
import insertUser from "../data/insertUser";

export default async function createUser(
req: Request,
res: Response
) {
try {

if (
!req.body.name ||
!req.body.nickname ||
!req.body.email
) {
throw new Error('Preencha os campos "name","nickname" e "email"')
}

const id: string = Date.now() + Math.random().toString()

await insertUser(
id,
req.body.name,
req.body.nickname,
req.body.email
)

res
.status(200)
.send('Usuário criado com sucesso!')

} catch (error) {
res.status(400).send({
message: error.message || error.sqlMessage
})
}
}
38 changes: 38 additions & 0 deletions Backend/Semana4/aula1/Intro_autenticacao/src/endpoints/editUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Request, Response } from "express";
import updateUser from "../data/updateUser";

export default async function editUser(
req: Request,
res: Response
) {
try {
if (
req.body.name === '' ||
req.body.nickname === '' ||
req.body.email === ''
) {
throw new Error("Nenhum dos campos pode estar em branco")
}

if (!req.body.name && !req.body.nickname && !req.body.email) {
throw new Error("Escolha ao menos um valor para alterar")
}

await updateUser(
req.params.id,
req.body.name,
req.body.nickname,
req.body.email
)


res.status(200).send({
message: "Usuário atualizado!"
})

} catch (error) {
res.status(400).send({
message: error.message || error.sqlMessage
})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Request, Response } from "express";
import selectTaskById from "../data/selectTaskById";

export default async function getTaskById(
req: Request,
res: Response
) {
try {
const result = await selectTaskById(req.params.id)

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

res.status(200).send({
id: result.id,
title: result.title,
description: result.description,
deadline: result.deadline,
status: result.status,
authorId: result.author_id,
authorNickname: result.nickname
})

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