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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.env
build
package-lock.json
node_modules
4 changes: 0 additions & 4 deletions README.md

This file was deleted.

31 changes: 31 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "template-lama",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "tsc && node ./build/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^11.0.0",
"express": "^4.17.2",
"jsonwebtoken": "^8.5.1",
"knex": "^0.95.15",
"mysql": "^2.18.1",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/jsonwebtoken": "^8.5.7",
"@types/knex": "^0.16.1",
"@types/uuid": "^8.3.4",
"typescript": "^4.5.4"
}
}
41 changes: 41 additions & 0 deletions src/buisiness/bandBuisiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { BandDatabase } from "../data/bandDatabase"
import { Authenticator } from "../services/tokenGenerator"
import { Band } from "../model/band";
import { IdGenerator } from "../services/idGenerator";
import { authenticationData } from "../services/tokenGenerator";

export class BandBuisiness {

createBand = async (
name: string,
mainGenre: string,
responsible: string,
token: string
) => {

const tokenData = new Authenticator().getTokenData(token)

if (tokenData?.role !== "ADMIN") {
throw new Error("Funçao disponível apenas para administradores")
}

if (!name || !mainGenre || !responsible) {
throw new Error("Preencha todos os campos de registro")
}

const id = new IdGenerator().generate()
const band = new Band(id, name, mainGenre, responsible)
await new BandDatabase().createBand(band)
}

getBandDetail = async (idOrName: string): Promise<Band> => {

if(!idOrName) {
throw new Error("Preencha o campo de pesquisa")
}

const band = await new BandDatabase().getBandDetail(idOrName)

return band
}
}
41 changes: 41 additions & 0 deletions src/buisiness/showBuisiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { BandDatabase } from "../data/bandDatabase"
import { ShowDatabase } from "../data/showDatabase"
import { Show } from "../model/show"
import { IdGenerator } from "../services/idGenerator"
import { Authenticator } from "../services/tokenGenerator"

export class ShowBuisiness {

createShow = async (weekDay: string, startTime: number, endTime: number, bandId: string, token: string) => {

const tokenData = new Authenticator().getTokenData(token)

if (tokenData.role !== "ADMIN") {
throw new Error("Função disponível apenas para administradores")
}

if (!weekDay || !startTime || !endTime || !bandId) {
throw new Error("Preencha todos os campos")
}

if (startTime < 8 || endTime > 23 || startTime >= endTime) {
throw new Error("Confira os horários")
}

if (!Number.isInteger(startTime) || !Number.isInteger(endTime)) {
throw new Error("Shows apenas em horas inteiras")
}

const bandFromDB = await new BandDatabase().getBandDetail(bandId)

if (!bandFromDB) {
throw new Error("Banda não encontrada")
}

const id = new IdGenerator().generate()

const show = new Show(id, weekDay, bandId, startTime, endTime)

await new ShowDatabase().createShow(show)
}
}
46 changes: 46 additions & 0 deletions src/buisiness/userBuisiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { UserDatabase } from "../data/userDatabase"
import { User } from "../model/user"
import { HashManager } from "../services/hashGenerator"
import { IdGenerator } from "../services/idGenerator"
import { Authenticator } from "../services/tokenGenerator"

export class UserBuisiness {

signup = async (
name: string,
email: string,
password: string,
role: string
): Promise<string> => {

const id = new IdGenerator().generate()

const hashPassword = await new HashManager().createHash(password)

const newUser = new User(id, name, email, hashPassword, role)

await new UserDatabase().signup(newUser)

const token = new Authenticator().generateToken({ id, role })

return token
}

login = async (
email: string,
password: string
): Promise<string | undefined> => {

const checkedUserEmail = await new UserDatabase().login(email)

const checkedPassword = await new HashManager().compareHash(password, checkedUserEmail.getPassword())

if (!checkedPassword) {
throw new Error("Senha incorreta")
}

const token = new Authenticator().generateToken({ id: checkedUserEmail.getId(), role: checkedUserEmail.getRole() })

return token
}
}
13 changes: 13 additions & 0 deletions src/controller/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import express, { Express } from "express"
import cors from "cors"

const app: Express = express()

app.use(express.json())
app.use(cors())

app.listen(3003, () => {
console.log("Ready!")
})

export default app
40 changes: 40 additions & 0 deletions src/controller/bandController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Response, Request } from "express";
import { BandBuisiness } from "../buisiness/bandBuisiness";

export class BandController {

createBand = async (
req: Request,
res: Response
) => {
try {

const { name, mainGenre, responsible } = req.body

const token = req.headers.authorization as string

await new BandBuisiness().createBand(name, mainGenre, responsible, token)

res.status(200).send("Banda registrada")
} catch (error: any) {
res.status(500)
.send({ error: error.message })
}
}

getBandDetail = async (
req: Request,
res: Response
) => {
try {
const input = (req.query.id ?? req.query.name) as string

const band = await new BandBuisiness().getBandDetail(input)

res.status(200).send(band)
} catch (error: any) {
res.status(error.customErrorCode || 400)
.send({ message: error.message })
}
}
}
25 changes: 25 additions & 0 deletions src/controller/showController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Response, Request } from "express";
import { ShowBuisiness } from "../buisiness/showBuisiness";
import { Show } from "../model/show";

export class ShowController {

createShow = async (
req: Request,
res: Response
) => {

try {

const { weekDay, bandId, startTime, endTime } = req.body

const token = req.headers.authorization as string

await new ShowBuisiness().createShow(weekDay, startTime, endTime, bandId, token)

res.status(200).send("Show agendado")
} catch (error: any) {
res.status(error.customErrorCode || 400).send({ message: error.message })
}
}
}
37 changes: 37 additions & 0 deletions src/controller/userController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Request, Response } from "express";
import { UserBuisiness } from "../buisiness/userBuisiness";

export class UserController {

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

const { name, email, password, role } = req.body

const result = await new UserBuisiness().signup(name, email, password, role)

res.status(200).send(result)
} catch (error: any) {
res.status(500).send("Falha interna")
}
}

login = async (
req: Request,
res: Response
) => {
try {

const { email, password } = req.body

const result = await new UserBuisiness().login(email, password)

res.status(200).send({ result })
} catch (error: any) {
res.status(500).send({error: error.message})
}
}
}
42 changes: 42 additions & 0 deletions src/data/bandDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { response } from "express";
import { Band } from "../model/band";
import { BaseDatabase } from "./baseDatabase";

export class BandDatabase extends BaseDatabase {

createBand = async (band: Band): Promise<void> => {
try {

await this.connection("bands")
.insert({
id: band.getId(),
name: band.getName(),
music_genre: band.getMainGenre(),
responsible: band.getResponsible()
})

} catch (error: any) {
throw new Error(error.sqlMessage || error.message)
}
}

getBandDetail = async (idOrName: string) => {
try {

const result = await this.connection("bands")
.select("*")
.where({ id: idOrName })
.orWhere({ name: idOrName })

if (!result[0]) {
throw new Error("Não encontramos esta banda nos registros")
}

const band = new Band(result[0].id, result[0].name, result[0].music_genre, result[0].responsible)

return band
} catch (error: any) {
throw new Error(error.sqlMessage || error.message)
}
}
}
17 changes: 17 additions & 0 deletions src/data/baseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import knex from "knex";
import dotenv from "dotenv";

dotenv.config()

export class BaseDatabase {
protected connection = knex({
client: "mysql",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_SCHEMA,
port: 3306
}
})
}
35 changes: 35 additions & 0 deletions src/data/showDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ShowBuisiness } from "../buisiness/showBuisiness";
import { Show } from "../model/show";
import { BaseDatabase } from "./baseDatabase";

export class ShowDatabase extends BaseDatabase {

createShow = async (show: Show): Promise<void> => {

try {
await this.connection("shows")
.insert({
id: show.getId(),
band_id: show.getBandId(),
start_time: show.getStartTime(),
end_time: show.getEndTime(),
week_day: show.getWeekDay()
})
} catch (error: any) {
throw new Error(error.sqlMessage || error.message)
}
}

getShowByTime = async (weekDay: string, startTime: number, endTime: number) => {

const result = await this.connection.raw(
`
SELECT * FROM shows
WHERE week_day = "${weekDay}
AND WHERE start_time <= "${endTime}
AND WHERE end_time >= "${startTime}`
)
}
}

// WHERE Country='Mexico'
Loading