Skip to content

Commit

Permalink
rotas, controladores e middlewares feitos
Browse files Browse the repository at this point in the history
  • Loading branch information
verissimon committed Oct 3, 2023
1 parent 7dd1609 commit ad9264c
Show file tree
Hide file tree
Showing 13 changed files with 266 additions and 40 deletions.
10 changes: 10 additions & 0 deletions src/@types/express.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import UserBody from './data/typeDefinitions'

declare global {
namespace Express {
interface Request {
username?: UserBody.username;
}
}
}

89 changes: 89 additions & 0 deletions src/controller/techController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Technology } from "../data/typeDefinitions";
import users from "../data/database";
import { Request, Response } from "express";
import { v4 as uuid } from "uuid";
import { BadRequestError } from "../helpers/apiErrors";

const listUserTechs = (req: Request, res: Response) => {
const { username } = req.headers;
const user = users.find( uname =>
uname.username === username as string
)
return res.json(user?.technologies);
}

const createUserTech = (req: Request, res: Response) => {
const { username } = req.headers
const { title, deadline } = req.body
const user = users.find( uname =>
uname.username === username as string)

const techExists = user?.technologies.find(
tech => tech.title === title)
if(techExists)
throw new BadRequestError("Technology already exists for this user")

if(!title || !deadline){
throw new BadRequestError("Title and deadline are required")
}

const technology: Technology = {
id: uuid(),
title: title,
studied: false,
deadline: new Date(deadline),
created_at: new Date(),
}

user?.technologies.push(technology)
return res.status(201).json(technology)
}

const updateTitleDeadline = (req: Request, res: Response) => {
const { username } = req.headers
const { id } = req.params
const { title, deadline } = req.body
if (!title || !deadline) {
throw new BadRequestError("Title or deadline are required")
}
const user = users.find( uname =>
uname.username === username as string)

user?.technologies.map((tech) => {
if (tech.id === id) {
tech.title = title
tech.deadline = deadline
}
return res.json({ message: "update feito com sucesso" })
})
}

const updateStudied = (req: Request, res: Response) => {
const { username } = req.headers
const { id } = req.params
const user = users.find( uname => uname.username === username as string)
user?.technologies.map( tech => {
if (tech.id === id)
tech.studied = !tech.studied
})
return res.json({ message: "update feito com sucesso" })
}

const deleteTech = (req: Request, res: Response) => {
const { username } = req.headers
const { id } = req.params
const user = users.find( uname => uname.username === username as string)
const tech = user?.technologies.find(
tech => tech.id === id)
const index = user?.technologies.indexOf(tech as Technology)
user?.technologies.splice(index!, 1)
return res.json({ message: "tecnologia deletada com sucesso" })
}

export const techController = {
listUserTechs,
createUserTech,
updateTitleDeadline,
updateStudied,
deleteTech
}
26 changes: 26 additions & 0 deletions src/controller/userController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { UserBody } from "../data/typeDefinitions";
import users from "../data/database";
import { Request, Response } from "express";
import { v4 as uuid } from 'uuid'

const addUser = (req: Request, res: Response) => {
const { name, username } = req.body as UserBody

const newUser: UserBody = {
id: uuid(),
name,
username,
technologies: []
}
users.push(newUser)
return res.status(201).json(newUser)
}

const listUsers = (req: Request, res: Response) => {
res.status(200).json(users);
}

export const UserController = {
addUser, //create
listUsers, //read
}
5 changes: 5 additions & 0 deletions src/data/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { UserBody } from "./typeDefinitions";

const users = [] as UserBody[]

export default users
15 changes: 15 additions & 0 deletions src/data/typeDefinitions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export type Technology = {
id: string,
title: string,
studied: boolean,
deadline: Date,
created_at: Date
}

export type UserBody = {
id: string,
name: string,
username: string,
technologies: Technology[]
}

26 changes: 26 additions & 0 deletions src/helpers/apiErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export class ApiError extends Error {
public readonly statusCode!: number;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
}
}

export class BadRequestError extends ApiError {
constructor(message = "Bad Request") {
super(message, 400);
}
}

export class NotFoundError extends ApiError {
constructor(message = "Bad Request") {
super(message, 404);
}
}

export class InternalServerError extends ApiError {
constructor(message = "Internal Server Error") {
super(message, 500);
}
}

50 changes: 10 additions & 40 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,18 @@
import { UUID } from 'crypto'
import express from 'express'
import { v4 as uuid } from 'uuid'
import userRoutes from "./routes/userRoutes"
import techRoutes from "./routes/techRoutes"
import { errorMiddleware } from "./middlewares/error";

const server = express()
server.use(express.json())

type Technology = {
title: string,
deadline: Date
}

type UserBody = {
id: string,
name: string,
username: string,
technologies: Technology[]
}

const users = [] as UserBody[]

// rotas relacionadas a usuario
server.post('/users', (req, res) => {
const { name, username } = req.body as UserBody

const userExists = users.some( user => user.username === username )

if(userExists)
return res.status(400).json({error: 'ja existe'})


const newUser: UserBody = {
id: uuid(),
name,
username,
technologies: []
}
users.push(newUser)
return res.status(201).json(newUser)
})

// rotas relacionadas com a tecnologias do usuario
server.use(express.json())
server.use(errorMiddleware)

server.use("/user", userRoutes);
server.use("/technologies", techRoutes)

const port = 3000
const port = 3001
server.listen(port, () => {
console.log(`server online on port ${port}`);
})
})

16 changes: 16 additions & 0 deletions src/middlewares/checkExistsUserAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Request, Response, NextFunction } from "express";
import users from "../data/database"
import { NotFoundError } from "../helpers/apiErrors";

export const checkExistsUserAccount = (
req: Request,
res: Response,
next: NextFunction
) => {
const { username } = req.headers
const user = users.find( ubody => ubody.username === username)
if (!user) {
throw new NotFoundError("User not found")
}
next()
}
18 changes: 18 additions & 0 deletions src/middlewares/checkTechIdExists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Request, Response, NextFunction } from "express";
import users from "../data/database"
import { NotFoundError } from "../helpers/apiErrors";

export const checkTechIdExists = (
req: Request,
res: Response,
next: NextFunction
) => {
const { username } = req.headers
const { id } = req.params
const user = users.find( ubody => ubody.username === username)
const techExists = user?.technologies.find(
tech => tech.id === id)
if(!techExists)
throw new NotFoundError("technology does not exist for this user")
next()
}
13 changes: 13 additions & 0 deletions src/middlewares/checkValidNewUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Request, Response, NextFunction } from "express"
import { UserBody } from "../data/typeDefinitions"
import users from "../data/database"

export const checkValidNewUser = (req: Request, res: Response, next: NextFunction) => {
const { username } = req.body as UserBody
const userExists = users.some( user => user.username === username )

if(userExists)
return res.status(400).json({error: 'Usuário já existe'})

next()
}
14 changes: 14 additions & 0 deletions src/middlewares/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Request, Response, NextFunction } from "express";
import { ApiError } from "../helpers/apiErrors";

export const errorMiddleware = (
error: Error & Partial<ApiError>,
req: Request,
res: Response,
next: NextFunction
) => {
const statusCode = error.statusCode ?? 500;
const message = error.statusCode ? error.message : "Internal server error";
return res.status(statusCode).json({ message });
};

14 changes: 14 additions & 0 deletions src/routes/techRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Router } from "express";
import { checkExistsUserAccount } from "../middlewares/checkExistsUserAccount";
import { checkTechIdExists } from "../middlewares/checkTechIdExists";
import { techController } from "../controller/techController";

const router = Router()

router.get('/', checkExistsUserAccount, techController.listUserTechs)
router.post('/', checkExistsUserAccount, techController.createUserTech)
router.put("/:id", checkExistsUserAccount, checkTechIdExists, techController.updateTitleDeadline)
router.patch("/:id/studied", checkExistsUserAccount, checkTechIdExists, techController.updateStudied)
router.delete("/:id", checkExistsUserAccount, checkTechIdExists, techController.deleteTech)

export default router
10 changes: 10 additions & 0 deletions src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Router } from "express";
import { checkValidNewUser } from "../middlewares/checkValidNewUser";
import { UserController } from "../controller/userController";

const router = Router()

router.post('/', checkValidNewUser, UserController.addUser)
router.get('/', UserController.listUsers)

export default router

0 comments on commit ad9264c

Please sign in to comment.