Skip to content

Teste Concluido #106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
20 changes: 20 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
#TODO Configure o Dockerfile
#imagem oficial do Node.js como base
FROM node:20

# Define o diretório de trabalho dentro do contêiner
WORKDIR /app

# Copia o package.json e o package-lock.json para o contêiner
COPY package*.json ./

# Instala as dependências
RUN npm install

# Copia o restante dos arquivos da aplicação para o contêiner
COPY . .

# Expõe a porta que o servidor usa
EXPOSE 3000

# Comando para iniciar o servidor
CMD ["npx", "ts-node", "src/index.ts"]
6 changes: 3 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
version: '3.8'

services:
api:
app:
build: .
ports:
- "3000:3000"
environment:
- DB_HOST=db
- DB_USER=root
- DB_PASSWORD=password
- DB_PASSWORD=1q2w3e
- DB_NAME=test_db
depends_on:
- db
Expand All @@ -17,7 +17,7 @@ services:
db:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_ROOT_PASSWORD=1q2w3e
- MYSQL_DATABASE=test_db
ports:
- "3306:3306"
Expand Down
18 changes: 16 additions & 2 deletions init.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
USE test_db;

--TODO Crie a tabela de user;
--Tabela 'User'
CREATE TABLE user(
id INT AUTO_INCREMENT PRIMARY KEY,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);

--TODO Crie a tabela de posts;
-- Tabela 'post'
CREATE TABLE post(
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
description VARCHAR(100) NOT NULL,
userId INT NOT NULL,
FOREIGN KEY (userId) REFERENCES user(id)

);
3 changes: 2 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
"test": "ts-node src/db.test.ts"
},
"dependencies": {
"express": "^4.18.2",
"axios": "^1.5.0",
"express": "^4.21.1",
"mysql2": "^3.6.1",
"typeorm": "^0.3.17",
"reflect-metadata": "^0.1.13",
"axios": "^1.5.0"
"typeorm": "^0.3.17"
},
"devDependencies": {
"@types/express": "^4.17.17",
Expand Down
15 changes: 14 additions & 1 deletion src/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

//TODO Crie a entidade de Post
export class Post {
id: number;
title: string;
description: string;
userId: number;

constructor(id: number, title: string, description: string, userId: number) {
this.id = id;
this.title = title;
this.description = description;
this.userId = userId;
}
}

14 changes: 13 additions & 1 deletion src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

//TODO Crie a entidade de User
export class User{
id: number;
firstName: string;
lastName: string;
email: string;

constructor(id: number, firstName:string, lastName:string, email:string){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
70 changes: 58 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'reflect-metadata';
import express from 'express';
import { DataSource } from 'typeorm';
import { User } from './entity/User';
import { Post } from './entity/Post';
import "reflect-metadata";
import express from "express";
import { DataSource } from "typeorm";
import { User } from "./entity/User";
import { Post } from "./entity/Post";

const app = express();
app.use(express.json());
Expand All @@ -12,13 +12,13 @@ const AppDataSource = new DataSource({
host: process.env.DB_HOST || "localhost",
port: 3306,
username: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "password",
password: process.env.DB_PASSWORD || "1q2w3e",
database: process.env.DB_NAME || "test_db",
entities: [User,Post],
entities: [User, Post],
synchronize: true,
});

const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const initializeDatabase = async () => {
await wait(20000);
Expand All @@ -33,12 +33,58 @@ const initializeDatabase = async () => {

initializeDatabase();

app.post('/users', async (req, res) => {
// Crie o endpoint de users
app.post("/users", async (req, res) => {
//endpoint de users
const { firstName, lastName, email } = req.body;

//verifica se os campos foram preenchidos
if (!firstName || !lastName || !email) {
return res.status(400).json({ error: "Missing required fields" });
}
//cria um novo user
const user = AppDataSource.manager.create(User, {
firstName,
lastName,
email,
});

//salva o usuário no banco
try {
const savedUser = await AppDataSource.manager.save(user);
res.status(201).json(savedUser);
} catch (err) {
console.error("Error saving user:", err);
res.status(500).json({ error: "Failed to save user" });
}
});

app.post('/posts', async (req, res) => {
// Crie o endpoint de posts
app.post("/posts", async (req, res) => {
//endpoint de posts
const { title, description, userId } = req.body;

//verifica se existe o usuário
try {
const user = await AppDataSource.manager.findOne(User, {
where: { id: userId },
});
if (!user) {
return res.status(404).json({ error: "User not found" });
}

//cria uma novo Post
const post = AppDataSource.manager.create(Post, {
title,
description,
userId,
});

//salva o post no banco
const savedPost = await AppDataSource.manager.save(post);
res.status(201).json(savedPost);
} catch (err) {
console.error("Error saving post:", err);
res.status(500).json({ error: "Failed to save post" });
}
});

const PORT = process.env.PORT || 3000;
Expand Down