Skip to content

Commit

Permalink
Added post room route for API
Browse files Browse the repository at this point in the history
Created the code for adding a new republic to the database via API
  • Loading branch information
pedroeverton217 committed Aug 27, 2024
1 parent 23c7d3e commit b6a2990
Showing 1 changed file with 36 additions and 10 deletions.
46 changes: 36 additions & 10 deletions api.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
//connection with the database
const mysql = require('mysql2/promise');

const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'unirepdb_basic'
});

db.connect((err) => {
if (err) {
console.error('Erro ao conectar ao banco de dados:', err);
} else {
console.log('Conectado ao banco de dados MySQL');
}
});

const express = require('express');
const app = express();
const path = require('path');
Expand Down Expand Up @@ -45,21 +63,29 @@ app.get('/api/v1/rooms/:id', (req, res) => {
});

// Create one room
app.post("/api/v1/rooms", async (req, res) => {
app.post('/api/v1/rooms', async (req, res) => {
const { nome, cep, complemento, numero, emaildono } = req.body;

// Validação básica
if (!nome || !cep || !numero || !emaildono) {
return res.status(400).json({ message: "Preencha todos os campos obrigatórios" });
}

try {
const [result] = await db.execute(
`INSERT INTO REPUBLICA (nome, cep, complemento, numero, emaildono)
VALUES (?, ?, ?, ?, ?)`,
[nome, cep, complemento, numero, emaildono]
);

} catch (error) {
console.log(error)
res.status(201).json({ message: "República criada com sucesso!", idRepublica: result.insertId });
} catch (err) {
console.error("Erro ao criar república:", err);
res.status(500).json({ message: "Erro ao criar república" });
}
console.log(req.body);
res.status(201).json({
status: "success",
data: {
room: "005"
}
});
});


// Update one room
app.put("/api/v1/rooms/:id", (req, res) => {
console.log(req.params.id);
Expand Down

0 comments on commit b6a2990

Please sign in to comment.