Skip to content

Commit

Permalink
Merge pull request #69 from mdsreq-fga-unb/54-adicionar-drill
Browse files Browse the repository at this point in the history
Integração das USs 50, 54, 61, 58 e 57 ao sistema
  • Loading branch information
luciano-freitas-melo authored Dec 7, 2023
2 parents e46f9fb + e56833f commit 57106c5
Show file tree
Hide file tree
Showing 30 changed files with 2,757 additions and 16,073 deletions.
22 changes: 11 additions & 11 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint",
"editor.formatOnPaste": false, // required
"editor.formatOnType": false, // required
"editor.formatOnSave": true, // optional
"editor.formatOnSaveMode": "file", // required to format on save
"files.autoSave": "onFocusChange", // optional but recommended
"vs-code-prettier-eslint.prettierLast": true,
"[typescript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
} // set as "true" to run 'prettier' last not first
}
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint",
"editor.formatOnPaste": false, // required
"editor.formatOnType": false, // required
"editor.formatOnSave": true, // optional
"editor.formatOnSaveMode": "file", // required to format on save
"files.autoSave": "onFocusChange", // optional but recommended
"vs-code-prettier-eslint.prettierLast": true,
"[typescript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
} // set as "true" to run 'prettier' last not first
}
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"test:watch": "jest --passWithNoTests --watch",
"test:stage": "jest --passWithNoTests --findRelatedTests",
"test:coverage": "jest --passWithNoTests --coverage",
"lint": "eslint --ext .ts ./src"
"lint": "eslint --ext .ts ./src",
"prettier": "prettier . --write"
},
"keywords": [],
"author": "",
Expand Down
13 changes: 13 additions & 0 deletions backend/prisma/migrations/20231128010441_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE "Drill" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT NOT NULL,
"observations" TEXT NOT NULL,
"classPlanId" TEXT NOT NULL,

CONSTRAINT "Drill_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "Drill" ADD CONSTRAINT "Drill_classPlanId_fkey" FOREIGN KEY ("classPlanId") REFERENCES "ClassPlan"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- You are about to drop the column `level` on the `User` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "User" DROP COLUMN "level";
11 changes: 10 additions & 1 deletion backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ model User {
name String
email String @unique
password String
level String @default("user")
classPlans ClassPlan[]
}

Expand All @@ -24,4 +23,14 @@ model ClassPlan {
createdAt DateTime @default(now())
userId String
user User @relation(fields: [userId], references: [id])
drills Drill[]
}

model Drill {
id String @id @default(uuid())
title String
description String
observations String
classPlanId String
classPlan ClassPlan @relation(fields: [classPlanId], references: [id])
}
55 changes: 55 additions & 0 deletions backend/src/controllers/classPlanController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,59 @@ export default class classPlanController {
}
}
}
list = async (req: Request, res: Response) => {
try {
const classPlan = await prisma.classPlan.findMany({
include: {
user: {
select: {
id: true,
email: true,
name: true,
},
},
},
})
res.status(200).json(classPlan)
} catch (err) {
res.status(500).json({ error: "Internal Server Error" })
}
}
show = async (req: Request, res: Response) => {
try {
const { id } = req.params
const classPlan = await prisma.classPlan.findUnique({
where: {
id: id,
},
include: {
user: {
select: {
id: true,
email: true,
name: true,
},
},
},
})
res.status(200).json(classPlan)
} catch (err) {
res.status(500).json({ error: "Internal Server Error" })
}
}

delete = async (req: Request, res: Response) => {
try {
const { id } = req.params

const classPlan = await prisma.classPlan.delete({
where: { id },
})

res.status(200).json(classPlan)
} catch (err) {
err as Prisma.PrismaClientKnownRequestError
res.status(500).json({ errors: { server: "Server error" } })
}
}
}
108 changes: 108 additions & 0 deletions backend/src/controllers/drillController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { Request, Response } from "express"
import { prisma } from "@/prisma"
import { ZodError } from "zod"
import { drillSchema } from "@/zodSchemas/drill.zod"
import { fromZodError } from "zod-validation-error"
import { Prisma } from "@prisma/client"

export default class drillController {
create = async (req: Request, res: Response) => {
try {
const data = drillSchema.parse(req.body)
const drill = (await prisma.drill.create({
data: {
...data,
},
include: {
classPlan: {
select: {
id: true,
},
},
},
})) as Prisma.DrillCreateInput
res.status(201).json(drill)
} catch (err) {
if (err instanceof ZodError) {
res.status(400).json(fromZodError(err))
} else {
res.status(500).json({ error: "Internal Server Error" })
}
}
}

getManyByClassPlanId = async (req: Request, res: Response) => {
try {
const { classPlanId } = req.params
const drills = await prisma.drill.findMany({
where: {
classPlanId,
},
select: {
id: true,
title: true,
},
})
res.status(200).json(drills)
} catch (err) {
res.status(500).json({ error: "Internal Server Error" })
}
}

updateById = async (req: Request, res: Response) => {
try {
const id = req.params.id
const data = drillSchema.parse(req.body)
const updatedDrill = await prisma.drill.update({
where: {
id,
},
data: {
...data,
},
})
res.status(204).json(updatedDrill)
} catch (err) {
if (err instanceof ZodError) {
res.status(400).json(fromZodError(err))
} else {
res.status(500).json({ error: "Internal Server Error" })
}
}
}

deleteById = async (req: Request, res: Response) => {
try {
const id = req.params.id
const deletedDrill = await prisma.drill.delete({
where: {
id,
},
})
res.status(204).json(deletedDrill)
} catch (err) {
res.status(500).json({ error: "Internal Server Error" })
}
}

show = async (req: Request, res: Response) => {
try {
const { id } = req.params
const drill = await prisma.drill.findUnique({
where: {
id: id,
},
include: {
classPlan: {
select: {
id: true,
},
},
},
})
res.status(200).json(drill)
} catch (err) {
res.status(500).json({ error: "Internal Server Error" })
}
}
}
7 changes: 2 additions & 5 deletions backend/src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ export default class userController {
if (b?.includes("email")) inputErr = { email: "Invalid email" }
if (b?.includes("username"))
inputErr = { username: "Username already exists" }
}

if (inputErr) res.status(400).json({ errors: inputErr })
else res.status(500).json({ errors: { server: "Server error" } })
if (inputErr) res.status(400).json({ errors: inputErr })
} else res.status(500).json({ errors: { server: "Server error" } })
}
}

Expand All @@ -61,14 +60,12 @@ export default class userController {

const token = authUser.generateToken({
id: user.id,
level: user.level,
})

res.status(200).json({
id: user.id,
name: user.name,
email: user.email,
level: user.level,
token,
})
} catch (err) {
Expand Down
1 change: 0 additions & 1 deletion backend/src/middleware/authUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { sign } from "jsonwebtoken"

interface Idata {
id: string
level: string
}

export default class AuthUser {
Expand Down
3 changes: 3 additions & 0 deletions backend/src/routes/classPlanRouters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ const classPlanRouters = Router()
const classPlan = new classPlanController()

classPlanRouters.post("/", classPlan.create)
classPlanRouters.get("/:id", classPlan.show)
classPlanRouters.get("/planos-usuario/:userId", classPlan.list)
classPlanRouters.delete("/:id", classPlan.delete)

export default classPlanRouters
13 changes: 13 additions & 0 deletions backend/src/routes/drillRouters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Router } from "express"
import drillController from "../controllers/drillController"

const drillRouters = Router()
const drill = new drillController()

drillRouters.post("/", drill.create)
drillRouters.get("/:classPlanId", drill.getManyByClassPlanId)
drillRouters.get("/drill/:id", drill.show)
drillRouters.put("/:id", drill.updateById)
drillRouters.delete("/:id", drill.deleteById)

export default drillRouters
2 changes: 2 additions & 0 deletions backend/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { Router } from "express"
import homeRoutes from "./homeRouters"
import userRoutes from "./userRouters"
import classPlanRouters from "./classPlanRouters"
import drillRouters from "./drillRouters"

const router = Router()

router.use("/", homeRoutes)
router.use("/user", userRoutes)
router.use("/classPlan", classPlanRouters)
router.use("/drill", drillRouters)

export { router }
14 changes: 14 additions & 0 deletions backend/src/zodSchemas/drill.zod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { z } from "zod"

const drillSchema = z.object({
title: z.string().min(5, "Título deve ter no mínimo 5 caracteres"),
description: z
.string()
.max(500, "Descrição deve ter no máximo 500 caracteres"),
observations: z
.string()
.max(500, "Observações deve ter no máximo 500 caracteres"),
classPlanId: z.string().uuid("Id do plano de aula inválido"),
})

export { drillSchema }
Loading

0 comments on commit 57106c5

Please sign in to comment.