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
2,943 changes: 2,943 additions & 0 deletions modulo5/laBook/package-lock.json

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions modulo5/laBook/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "aula-knex",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "tsc && node ./build/index.js",
"dev-start": "ts-node-dev ./src/index.ts"
},
"author": "Labenu",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"knex": "^0.95.2",
"mysql": "^2.18.1"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.10",
"@types/express": "^4.17.11",
"@types/jsonwebtoken": "^8.5.8",
"@types/knex": "^0.16.1",
"@types/node": "^14.14.35",
"@types/uuid": "^8.3.4",
"bcryptjs": "^2.4.3",
"jsonwebtoken": "^8.5.1",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.3",
"uuid": "^8.3.2"
}
}
10 changes: 10 additions & 0 deletions modulo5/laBook/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express, { Express } from "express"
import cors from "cors"

export const app: Express = express()
app.use(express.json())
app.use(cors())

app.listen(3003, () => {
console.log("Server running on port 3003")
})
45 changes: 45 additions & 0 deletions modulo5/laBook/src/business/PostBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { PostDatabase } from "../data/PostDatabase"
import { post, postDTO } from "../model/Post"
import { getTokenData } from "../services/authentication"
import { generateId } from "../services/generateId"
import {authenticationData} from "../services/authentication"

const postDatabase = new PostDatabase()

export class PostBusiness {

createPostBusiness = async ({ photo, description, type, token }:any ): Promise<any>=> {


const tokenData: authenticationData = getTokenData(token)

const id: string = generateId()

const newPost: postDTO = { id, photo, description, type, author_Id: tokenData.id }

await postDatabase.create(newPost)
}


getPostByIdBusiness = async ({id, token}:any): Promise<post> => {

const tokenData: authenticationData = getTokenData(token)

const queryResult: any = await postDatabase.getById(id)

if (!queryResult[0]) {
throw new Error(`"Post not found"`)
}

const post: post = {
id: queryResult[0].id,
photo: queryResult[0].photo,
description: queryResult[0].description,
type: queryResult[0].type,
createdAt: queryResult[0].created_at,
author_Id: queryResult[0].author_id,
}

return post
}
}
52 changes: 52 additions & 0 deletions modulo5/laBook/src/business/UserBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Request, Response} from "express"
import { generateToken } from "../services/authentication"
import { generateId } from "../services/generateId"
import { compare, hash } from "../services/hashManager"
import { UserDatabase } from "../data/UserDatabase"
import {user} from "../model/User"

const userDatabase = new UserDatabase()

export class UserBusiness {

signupBusiness = async ({ name, email, password }:any):Promise<any> => {

const id: string = generateId()

const cypherPassword:string = await hash(password);

const newUser = { id, name, email, password:cypherPassword}

await userDatabase.create(newUser)

const token: string = generateToken({ id })

return token
}

loginBusiness = async (
email: string,
password: string
) => {

if (!email || !password) {
throw new Error("Preencha todos os campos")
}
console.log(`busines`,email, password)
const user: user = await userDatabase.login(email)
if (!user) {
throw new Error("Usuário não encontrado")
}

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

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

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

return token

}
}
44 changes: 44 additions & 0 deletions modulo5/laBook/src/controller/PostController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Request, Response } from "express"
import { PostBusiness } from "../business/PostBusiness"
import { post } from "../model/Post"

const postBusiness = new PostBusiness()
export class PostController {

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

const { photo, description, type } = req.body
const token: string = req.headers.authorization as string

await postBusiness.createPostBusiness({ photo, description, type, token })

res.status(201).send({ message: `sucess` })

} catch (error: any) {
let message = error.sqlMessage || error.message
res.statusCode = 400

res.send({ message })
}
}

getPostById = async (req: Request, res: Response) => {
try {
let message = "Success!"

const { id } = req.params
const token = req.headers.authorization

const post = await postBusiness.getPostByIdBusiness({ id, token })

res.status(200).send({ message, post })

} catch (error: any) {
let message = error.sqlMessage || error.message
res.statusCode = 400

res.send({ message })
}
}
}
54 changes: 54 additions & 0 deletions modulo5/laBook/src/controller/UserController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Request, Response } from "express"
import { UserBusiness } from "../business/UserBusiness"

const userBusiness = new UserBusiness()

export class UserController {

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

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

let message = "Success!"

if (!name || !email || !password) {
res.statusCode = 406
message = '"name", "email" and "password" must be provided'
throw new Error(message)
}


const token = await userBusiness.signupBusiness({ name, email, password })

res.status(201).send({ message, token })

} catch (error: any) {
res.statusCode = 400
let message = error.sqlMessage || error.message

res.send({ message })
}
}

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

const { email, password } = req.body

const token = await userBusiness.loginBusiness(email, password)

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

} catch (error: any) {
res.status(400).send(error.message)
}
}
}
19 changes: 19 additions & 0 deletions modulo5/laBook/src/data/BaseDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import knex, { Knex } from "knex";
import dotenv from "dotenv";


dotenv.config();

export class BaseDatabase {
protected static connection: Knex = knex({
client: "mysql",
connection: {
host: process.env.DB_HOST,
port: 3306,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_SCHEMA,
multipleStatements: true,
},
});
}
34 changes: 34 additions & 0 deletions modulo5/laBook/src/data/PostDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { postDTO } from "../model/Post";
import { BaseDatabase } from "./BaseDatabase";

export class PostDatabase extends BaseDatabase {

private static tablePost = "labook_posts"
async create({
id,
photo,
description,
type,
author_Id
}:postDTO) {
await BaseDatabase.connection()
.insert({
id,
photo,
description,
type,
author_Id
})
.into(PostDatabase.tablePost)
}

async getById (id:string){
const result = await BaseDatabase.connection()
.select("*")
.where({ id })
.from(PostDatabase.tablePost)

console.log(result)
return result
}
}
42 changes: 42 additions & 0 deletions modulo5/laBook/src/data/UserDatabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { query } from "express";
import { user } from "../model/User";
import { BaseDatabase } from "./BaseDatabase";

export class UserDatabase extends BaseDatabase{

private static UserTable = 'labook_users'

async create({
id,
name,
email,
password
}:user){

await BaseDatabase.connection.insert({
id,
name,
email,
password
})
.into(UserDatabase.UserTable)
}

async login (email:string){
const queryResult = await BaseDatabase.connection.select("*")
.where({ email })
.from(UserDatabase.UserTable)

if (!queryResult[0]) {
throw new Error("Invalid credentials")
}
const user: user = {
id: queryResult[0].id,
name: queryResult[0].name,
email: queryResult[0].email,
password: queryResult[0].password
}

return user
}
}
6 changes: 6 additions & 0 deletions modulo5/laBook/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {app} from "./app"
import { postRouter } from "./routes/postRouter"
import { userRouter } from "./routes/userRouter"

app.use("/users", userRouter)
app.use("/posts", postRouter)
22 changes: 22 additions & 0 deletions modulo5/laBook/src/model/Post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
enum POST_TYPES {
NORMAL = "normal",
EVENT = "event"
}

export type post = {
id: string,
photo: string,
description: string,
type: POST_TYPES,
createdAt: Date,
author_Id: string
}


export type postDTO = {
id: string,
photo: string,
description: string,
type: POST_TYPES,
author_Id: string
}
Loading