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

CletoCosta dev_test #93

Open
wants to merge 6 commits 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
7 changes: 7 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
#TODO Configure o Dockerfile
FROM node:16
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ services:
- DB_NAME=test_db
depends_on:
- db

entrypoint: ["./wait-for-it.sh", "db:3306", "--", "npm", "run", "dev"]

db:
image: mysql:8.0
Expand Down
14 changes: 13 additions & 1 deletion init.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
USE test_db;

--TODO Crie a tabela de 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;
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) ON DELETE CASCADE
);
20 changes: 18 additions & 2 deletions src/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

//TODO Crie a entidade de Post
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
import { User } from './User'; // Importando a entidade User

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

@Column()
title: string;

@Column()
description: string;

// Relacionamento "muitos para um" com a tabela User
@ManyToOne(() => User, (user) => user.posts)
user: User;
}
23 changes: 21 additions & 2 deletions src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

//TODO Crie a entidade de User
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Post } from './Post'; // Importando a entidade Post

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

@Column()
firstName: string;

@Column()
lastName: string;

@Column()
email: string;

// Relacionamento "um para muitos" com a tabela Post
@OneToMany(() => Post, (post) => post.user)
posts: Post[];
}
48 changes: 44 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ 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,
});

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

const initializeDatabase = async () => {
await wait(20000);
await wait(20000); // Aguardar 20 segundos
try {
await AppDataSource.initialize();
console.log("Data Source has been initialized!");
Expand All @@ -34,14 +34,54 @@ const initializeDatabase = async () => {
initializeDatabase();

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

if (!firstName || !lastName || !email) {
return res.status(400).json({ message: "First Name, Last Name, and Email are required" });
}

try {
const user = new User();
user.firstName = firstName;
user.lastName = lastName;
user.email = email;

const result = await AppDataSource.manager.save(user);
res.status(201).json(result);
} 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
const { title, description, userId } = req.body;

if (!title || !description || !userId) {
return res.status(400).json({ message: "Title, Description, and UserId are required" });
}

try {
const user = await AppDataSource.manager.findOne(User, { where: { id: userId } });
if (!user) {
return res.status(404).json({ message: "User not found" });
}

const post = new Post();
post.title = title;
post.description = description;
post.user = user;

const result = await AppDataSource.manager.save(post);
res.status(201).json(result);
} catch (error) {
console.error("Error creating post:", error);
res.status(500).json({ message: "Error creating post" });
}
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});