Skip to content
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

Teste completo #111

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
35 changes: 35 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Node.js
node_modules/
npm-debug.log
yarn-error.log

# TypeScript
dist/
*.tsbuildinfo

# Docker
docker-compose.override.yml
.docker/

# Logs
*.log

# MySQL data
*.sql
*.sqlite

# Environment files
.env
.env.local
.env.*.local

# IDE files
.vscode/
.idea/

# OS-specific files
.DS_Store
Thumbs.db

# Coverage output
coverage/
12 changes: 12 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
#TODO Configure o Dockerfile
FROM node:18

WORKDIR /app

COPY package.json package-lock.json ./
RUN npm install

COPY . .

RUN npm run build

CMD ["npm", "start"]
16 changes: 13 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,30 @@ services:
- DB_USER=root
- DB_PASSWORD=password
- DB_NAME=test_db


depends_on:
- db

db:
condition: service_healthy # Garantindo a inicialização do banco e dos comandos necessários

entrypoint: ["npm", "run", "dev"]

db:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=test_db
ports:
- "3306:3306"
- "33062:3306" #Usando a porta 33062 pois meu pc usa a 33061 como entrada padrão do mysql fora do WSL2
volumes:
- mysql-data:/var/lib/mysql
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD", "mysql", "-uroot", "-ppassword", "-e", "SELECT 1"] #comandos necessários
interval: 10s
retries: 5
start_period: 30s
timeout: 10s

volumes:
mysql-data:
24 changes: 22 additions & 2 deletions init.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
USE test_db;

--TODO Crie a tabela de user;
-- Garantindo o usuário no container
CREATE USER IF NOT EXISTS 'root' @'%' IDENTIFIED BY 'password';

--TODO Crie a tabela de posts;
GRANT ALL PRIVILEGES ON *.* TO 'root' @'%' WITH GRANT OPTION;

FLUSH PRIVILEGES;

-- Criar a tabela de usuários
CREATE TABLE user (
id INT AUTO_INCREMENT PRIMARY KEY,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);

-- Criar a tabela de posts
CREATE TABLE post (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
description VARCHAR(100) NOT NULL,
userId INT NOT NULL,
CONSTRAINT FK_user FOREIGN KEY (userId) REFERENCES user (id)
);
19 changes: 18 additions & 1 deletion src/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';

//TODO Crie a entidade de Post
import { User } from './User';

@Entity()
export class Post {
@PrimaryGeneratedColumn()
id!: number;

@Column({ length: 100 })
title!: string;

@Column({ length: 100 })
description!: string;

@ManyToOne(() => User)
@JoinColumn({ name: 'userId' })
user!: User;
}
22 changes: 21 additions & 1 deletion src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";

//TODO Crie a entidade de User

import { Post } from "./Post";

@Entity()
export class User {
@PrimaryGeneratedColumn()
id!: number;

@Column({ length: 100 })
firstName!: string;

@Column({ length: 100 })
lastName!: string;

@Column({ length: 100 })
email!: string;

@OneToMany(() => Post, (post) => post.user)
posts!: Post[];
}
32 changes: 29 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const AppDataSource = new DataSource({
username: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "password",
database: process.env.DB_NAME || "test_db",
entities: [User,Post],
entities: [User, Post],
synchronize: true,
});

Expand All @@ -34,11 +34,37 @@ const initializeDatabase = async () => {
initializeDatabase();

app.post('/users', async (req, res) => {
// Crie o endpoint de users
// Crie o endpoint de users
try {
const userRepository = AppDataSource.getRepository(User);
const user = userRepository.create(req.body);
const savedUser = await userRepository.save(user);
res.status(201).json(savedUser);
} catch (error) {
console.error("Error creating user:", error);
res.status(500).json({ message: "Error creating user" });
}
});

app.post('/posts', async (req, res) => {
// Crie o endpoint de posts
// Crie o endpoint de posts
try {
const { userId, title, description } = req.body;
const userRepository = AppDataSource.getRepository(User);
const postRepository = AppDataSource.getRepository(Post);

const user = await userRepository.findOneBy({ id: userId });
if (!user) {
return res.status(404).json({ message: "User not found" });
}

const post = postRepository.create({ title, description, user });
const savedPost = await postRepository.save(post);
res.status(201).json(savedPost);
} catch (error) {
console.error("Post error:", error);
res.status(500).json({ message: "Error creating post" });
}
});

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