Skip to content

Commit

Permalink
refactor : configurando API vps
Browse files Browse the repository at this point in the history
  • Loading branch information
whalterduarte committed May 6, 2024
1 parent 8ff0ae4 commit 10ec296
Show file tree
Hide file tree
Showing 48 changed files with 611 additions and 2,151 deletions.
23 changes: 23 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Use uma imagem Node.js como base
FROM node:alpine

# Defina o diretório de trabalho no contêiner
WORKDIR /usr/src/app/backend/portfolio

# Copie o conteúdo do diretório para dentro do contêiner
COPY . .

# Instale as dependências do aplicativo
RUN npm install

# Instale o nodemon globalmente
RUN npm install -g nodemon

# Instale o ts-node globalmente
RUN npm install -g ts-node

# Exponha a porta 4001 do contêiner (se necessário)
EXPOSE 4001

# Comando para iniciar o aplicativo quando o contêiner for iniciado
CMD ["npm", "start"]
2,466 changes: 471 additions & 1,995 deletions package-lock.json

Large diffs are not rendered by default.

15 changes: 6 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon -e ts,json,handlebars app.ts",
"start": "nodemon -e ts,json,app.ts --exec 'ts-node' app.ts",
"vercel-build": "npx prisma db push"
},
"keywords": [],
Expand All @@ -17,16 +17,14 @@
"@types/express": "^4.17.12",
"@types/jsonwebtoken": "^9.0.5",
"@types/multer": "^1.4.11",
"@types/multer-s3": "^3.0.3",
"@types/node": "^15.12.5",
"@types/sequelize": "^4.28.16",
"@types/node": "^15.14.9",
"@types/validator": "^13.1.4",
"prisma": "^5.6.0"
"nodemon": "^3.1.0",
"prisma": "^5.6.0",
"typescript": "^5.4.5"
},
"dependencies": {
"@prisma/client": "^5.6.0",
"@types/aws-sdk": "^2.7.0",
"aws-sdk": "^2.1520.0",
"axios": "^1.6.2",
"bcrypt": "^5.1.1",
"body-parser": "^1.20.2",
Expand All @@ -37,9 +35,8 @@
"handlebars": "^4.7.8",
"jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1",
"multer-s3": "^3.0.1",
"mysql2": "^3.6.1",
"path": "^0.12.7",
"pg": "^8.11.5",
"validator": "^13.6.0"
}
}
6 changes: 4 additions & 2 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
provider = "prisma-client-js"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
}


datasource db {
provider = "mysql"
provider = "postgresql"
url = env("DATABASE_URL")
}

Expand Down
Binary file added public/blog/photo-1714934336795.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934338511.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934361869.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934379835.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934442308.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934443750.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934455913.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934458567.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934517316.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934518353.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934521095.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934545428.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934547077.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934591961.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934592996.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934931355.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934933368.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934968154.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714934969589.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935088510.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935089459.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935090187.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935090994.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935104708.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935141603.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/blog/photo-1714935144746.jpg
Binary file added public/blog/photo-1714935156733.jpg
Binary file added public/blog/photo-1714935197402.jpg
Binary file added public/blog/photo-1714935201119.jpg
Binary file added public/project/project_2053779_1714935412722.jpg
Binary file added public/project/project_2951966_1714935283157.jpg
Binary file added public/project/project_3917908_1714935275008.jpg
Binary file added public/project/project_4986944_1714935435778.jpg
Binary file added public/project/project_5326256_1714935394389.jpg
Binary file added public/project/project_5961596_1714935358722.jpg
Binary file added public/project/project_9636217_1714935298926.jpg
Binary file added public/project/project_9724726_1714935422956.jpg
Binary file added public/project/project_9910411_1714935289357.jpg
Binary file added public/project/project_9950209_1714935450744.jpg
135 changes: 60 additions & 75 deletions src/controller/posts.controller.ts
Original file line number Diff line number Diff line change
@@ -1,131 +1,116 @@
import { Request, Response } from "express"
import prisma from "../libs/prisma"
import { Request, Response } from "express";
import prisma from "../libs/prisma";
import path from "path";

//Get list all Posts
export const getAllPosts = async (req:Request, res:Response) =>{
// Get list all Posts
export const getAllPosts = async (req: Request, res: Response) => {
try {
const posts = await prisma.post.findMany({ orderBy: { date: 'desc' }})
if(posts.length === 0) {
return res
.status(404)
.json({error: 'Não a nenhum post cadastrado'})
const posts = await prisma.post.findMany({ orderBy: { date: "desc" } });
if (posts.length === 0) {
return res.status(404).json({ error: "Não há nenhum post cadastrado" });
}
return res.json({success: true, posts})
return res.json({ success: true, posts });
} catch (error) {
console.log(error)
return res.status(500).json({ server: 'Erro interno', error })
console.log(error);
return res.status(500).json({ server: "Erro interno", error });
}
}

};

//Get all posts in the category
// Get all posts in the category
export const getPostsByCategory = async (req: Request, res: Response) => {
try {
const { name } = req.params
const { name } = req.params;

const category = await prisma.category.findUnique({
where: {
name
}
})
name,
},
});

if (!category) {
return res.status(404).json({ error: 'Categoria não encontrada' })
return res.status(404).json({ error: "Categoria não encontrada" });
}

const posts = await prisma.post.findMany({
where: {
categoryId: category.id
categoryId: category.id,
},
orderBy: { date: 'desc' }
})
orderBy: { date: "desc" },
});

if (posts.length === 0) {
return res.status(404).json({ error: 'Não há nenhum post cadastrado para esta categoria' })
return res
.status(404)
.json({ error: "Não há nenhum post cadastrado para esta categoria" });
}

return res.json({ success: true, posts })
return res.json({ success: true, posts });
} catch (error) {
console.error(error)
return res.status(500).json({ server: 'Erro interno', error })
} finally {
await prisma.$disconnect()
console.error(error);
return res.status(500).json({ server: "Erro interno", error });
}
}

};

//Get Post in category
// Get Post in category
export const getPostInCategory = async (req: Request, res: Response) => {
try {
const { name, slug } = req.params
const { name, slug } = req.params;
const category = await prisma.category.findUnique({
where: {
name: name,
},
})
});
if (!category) {
return res.status(404).json({ error: 'Categoria não encontrada' })
return res.status(404).json({ error: "Categoria não encontrada" });
}

const post = await prisma.post.findUnique({
where: {
slug: slug,
categoryId: category.id,
},
})
});
if (!post) {
return res.status(404).json({ error: 'Post não encontrado nesta categoria' })
return res
.status(404)
.json({ error: "Post não encontrado nesta categoria" });
}
return res.json({ success: true, post })
return res.json({ success: true, post });
} catch (error) {
console.error(error);
return res.status(500).json({ server: 'Erro interno', error })
} finally {
await prisma.$disconnect()
return res.status(500).json({ server: "Erro interno", error });
}
}
};

export const newPost = async (req: Request, res: Response) => {
interface UploadedFile {
fieldname: string;
originalname: string;
encoding: string;
mimetype: string;
destination: string;
filename: string;
path: string;
size: number;
}
//Accpts only image
if(req.file){
const file = req.file as UploadedFile
}else{
res.status(404).json({error: 'File not sent'})
return
}
//New Post
try {
const { title, slug, content, body, url, author, categoryId } = req.body
const photo: string = `${process.env.BASE}/${(req.file as Express.MulterS3.File)?.key}`;
if(!title || !slug || !content || !body || !author || !categoryId|| !photo) {
return res.json({Sever: 'Todos os campos são obrigatorios'})
}else{
try {
// Verifica se o arquivo foi enviado
if (!req.file) {
return res.status(400).json({ error: "File not sent" });
}

const { title, slug, content, body, author, categoryId } = req.body;

const photoPath = req.file.path; // Caminho do arquivo local

if (!title || !slug || !content || !body || !author || !categoryId || !photoPath) {
return res.json({ Sever: "Todos os campos são obrigatórios" });
} else {
await prisma.post.create({
data: {
title,
slug,
url: photo,
url: photoPath, // Atualiza o caminho do arquivo para o caminho local
content,
body,
author,
categoryId: parseInt(categoryId, 10),
},
})
return res.json({ success: 'Post criado com sucesso' });
});
return res.json({ success: "Post criado com sucesso" });
}
} catch (error) {
console.log('Erro ao criar post:', error)
return res.status(500).json({ Server: 'Erro interno do servidor' })
}

}
} catch (error) {
console.log("Erro ao criar post:", error);
return res.status(500).json({ Server: "Erro interno do servidor" });
}
};
3 changes: 2 additions & 1 deletion src/controller/projects.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ export const addProject = async (req:Request, res:Response) =>{

try {
const { linkgit, descproject, url, desc, title, body, slug, linkproject } = req.body
const photo: string = `${process.env.BASE}/${(req.file as Express.MulterS3.File)?.key}`;
const fileName: string = req.file.filename;
const photo: string = `${process.env.BASE}/project/${fileName}`;
if(!linkgit || !descproject || !desc || !title || !body || !slug || !linkproject || !photo) {
return res.json({Sever: 'Todos os campos são obrigatorios'})
}else{
Expand Down
61 changes: 20 additions & 41 deletions src/routes/blog.routes.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,27 @@
import { Router, Request, Response } from 'express'
import * as posts from '../controller/posts.controller'
import multer, { Multer } from 'multer'
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'
import multerS3 from 'multer-s3'
import { Auth } from '../middleware/auth'
import { Router } from 'express';
import * as posts from '../controller/posts.controller';
import multer, { Multer } from 'multer';
import path from 'path';


const s3Client = new S3Client({
region: process.env.AWS_REGION || 'sa-east-1',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || '',
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/blog'); // Define a pasta de destino como 'public/blog'
},
filename: function (req, file, cb) {
const ext = path.extname(file.originalname);
cb(null, file.fieldname + '-' + Date.now() + ext); // Define o nome do arquivo
},
})
});

const upload: Multer = multer({
storage: multerS3({
s3: s3Client,
bucket: process.env.BUCKET_NAME || '',
acl: 'public-read',
contentType: multerS3.AUTO_CONTENT_TYPE,
key: (req: Request, file, cb) => {
console.log('File Object:', file)
let randomNamePhoto = Math.floor(Math.random() * 9999999);
const originalname = file.originalname || 'default'
cb(null, 'uploads/' + originalname + randomNamePhoto + Date.now() + '.jpg')
},
}),
fileFilter: (req: Request, file: Express.Multer.File, cb) => {
const allowed: string[] = ['image/jpg', 'image/jpeg', 'image/png']
if (allowed.includes(file.mimetype)) {
cb(null, true)
} else {
cb(new Error('Invalid file type'))
}
}
})
const upload: Multer = multer({ storage: storage });

const router = Router()
const router = Router();

router.get('/posts', posts.getAllPosts)
router.get('/posts/:name', posts.getPostsByCategory)
router.get('/posts/:name/:slug', posts.getPostInCategory)
router.get('/posts', posts.getAllPosts);
router.get('/posts/:name', posts.getPostsByCategory);
router.get('/posts/:name/:slug', posts.getPostInCategory);

router.post('/admin/newpost', upload.single('photo'), posts.newPost)
// Altera o endpoint para /admin/newpost e utiliza o middleware de upload
router.post('/admin/newpost', upload.single('photo'), posts.newPost);

export default router;
export default router;
Loading

0 comments on commit 10ec296

Please sign in to comment.