eletrotupi / tcc/ commit / 36300f0

api/routes: basic rotues

Pedro Lucas Porcellis porcellis@eletrotupi.com · 10 months ago 36300f0d1b099080ea7e30ec28c85263f2dcb5c1 Browse files
Parents b25df90
Changed files
4
Additions
+80
Deletions
0
api/src/app.js modified+12
api/src/app.js
1 +
const express = require("express");
2 +
const app = express();
3 +

4 +
const users = require("./routes/users");
5 +
const mood = require("./routes/mood");
6 +

7 +
app.use(express.json());
8 +
app.use("/users", users);
9 +
app.use("/mood", mood);
10 +

11 +
module.exports = app;
12 +

api/src/db.js modified+4
api/src/db.js
1 +
const Database = require('better-sqlite3');
2 +
const db = new Database('orbit.db');
3 +

4 +
module.exports = db;
/dev/null → api/src/routes/mood.js
1 +
const express = require("express");
2 +
const db = require("../db");
3 +
const router = express.Router();
4 +

5 +
router.post("/", (req, res) => {
6 +
  const { user_id, stress_level, anxiety_level, title, description } = req.body;
7 +

8 +
  if (!user_id || !stress_level || !anxiety_level)
9 +
    return res.status(400).json({ error: "Campos fatlantes" });
10 +

11 +
  const stmt = db.prepare(
12 +
    `
13 +
      INSERT INTO mood (user_id, stress_level, anxiety_level, title, description)
14 +
      VALUES (?, ?, ?, ?, ?)
15 +
    `
16 +
  );
17 +

18 +
  const result = stmt.run(
19 +
    user_id, stress_level, anxiety_level, title || null, description || null
20 +
  );
21 +

22 +
  res.status(201).json({ id: result.lastInsertRowid });
23 +
});
24 +

25 +
router.get("/:user_id", (req, res) => {
26 +
  const stmt = db.prepare("SELECT * FROM mood WHERE user_id = ?");
27 +
  const rows = stmt.all(req.params.user_id);
28 +

29 +
  res.json(rows);
30 +
});
31 +

32 +
module.exports = router;
33 +

/dev/null → api/src/routes/users.js
1 +
const express = require("express");
2 +
const bcrypt = require("bcryptjs");
3 +
const db = require("../db");
4 +
const router = express.Router();
5 +

6 +
// XXX: Needs translations
7 +
router.post("/", (req, res) => {
8 +
  const { email, password, first_name, last_name } = req.body;
9 +
  if (!email || !password || !first_name || !last_name)
10 +
    return res.status(400).json({ error: "Campos faltantes" });
11 +

12 +
  const hashed = bcrypt.hashSync(password, 10);
13 +

14 +
  try {
15 +
    const stmt = db.prepare(
16 +
      `
17 +
        INSERT INTO users (email, password, first_name, last_name)
18 +
        VALUES (?, ?, ?, ?)
19 +
      `
20 +
    );
21 +

22 +
    const result = stmt.run(email, hashed, first_name, last_name);
23 +

24 +
    res.status(201).json({ id: result.lastInsertRowid });
25 +
  } catch (err) {
26 +
    res.status(400).json({ error: "Email já cadastrado" });
27 +
  }
28 +
});
29 +

30 +
module.exports = router;
31 +