Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
2.4 kB
1
Indexable
Never
const db = require("../data/database");
const Base = require("./base.model");

class Najomnik extends Base {
  static async fetchAll() {
    const query = `select * from najomnici`;
    const [records] = await db.query(query);
    return records;
  }

  async save() {
    const query = `
    INSERT INTO najomnici (nazovFirmy, cenaMesiac, platnostDo, object_id, user_id) VALUES (?)
    `;
    const [result] = await db.query(query, [
      [
        this.nazovFirmy,
        this.cenaMesiac,
        this.platnostDo,
        this.object_id,
        this.user_id,
      ],
    ]);
    return result;
  }



  static async getNajomnikById(id) {
    const query = "SELECT * from najomnici where id = ?";
    const [records] = await db.query(query, [id]);
    if (records.length > 0) {
      return new Object({ ...records[0] }, records[0].id);
    }
    return null;
  }

  async remove() {
    const query = "DELETE from najomnici where id = ?";
    await db.query(query, [this.id]);

  }

}





module.exports = Najomnik;


const Najomnik = require("../models/najomnici.model");

const getNajomniciList = async (req, res) => {
    const records = await Najomnik.fetchAll();
    res.render("najomnici/najomniciList", { records });
  };

  const getNajomnikForm = async (req, res) => {
    res.render("najomnici/najomnikFormular", { values: {}, action: `/najomnici/vytvorNaj` });
  };


  const createNajomnik = async (req, res) => {
    const { nazovFirmy, cenaMesiac, platnostDo, object_id } = req.body;
  
    const naj = new Najomnik({
      nazovFirmy,
      cenaMesiac,
      platnostDo,
      object_id,
      user_id: req.session.user.user_id,
    });
    await naj.save();
    res.redirect("/najomnici");
  };

  const getNajomnikDetails = async (req, res) => {
    const naj = await Najomnik.getNajomnikById(req.params.id);
    res.render("najomnici/najomnikDetails", {
      values: naj,
      action: `/najomnici/${naj.id}/edit`,
    });
  };

  const deleteNajomnik = async (req, res) => {
    const naj = await Najomnik.getNajomnikById(req.params.id);
    if (naj) {
      await naj.remove();
    }
    res.redirect("/najomnici");
  };

  module.exports= {
    getNajomniciList, getNajomnikForm, createNajomnik, getNajomnikDetails, deleteNajomnik
  };

Leave a Comment