const sql = require("./db.js");
// constructor
const custloc = function(cust) {
this.first_name = cust.first_name;
this.last_name = cust.last_name;
this.country_code = cust.country_code;
this.mobile = cust.mobile;
this.email = cust.email;
this.created_user_id = cust.created_user_id;
this.created_time = cust.created_time;
this.updated_user_id = cust.updated_user_id;
this.updated_time = cust.updated_time;
this.is_active = cust.is_active;
this.pw = cust.pw;
};
custloc.create = (newcustloc, result) => {
sql.query("INSERT INTO customers SET ?", newcustloc, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created cust: ", { id: res.insertId, ...newcustloc });
result(null, { id: res.insertId, ...newcustloc });
});
};
custloc.findById = (id, result) => {
sql.query(`SELECT * FROM customers WHERE id = ${id}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found cust: ", res[0]);
result(null, res[0]);
return;
}
// not found custloc with the id
result({ kind: "not_found" }, null);
});
};
custloc.getAll = result => {
sql.query("SELECT * FROM customers", (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("custs: ", res);
result(null, res);
});
};
custloc.updateById = (id, cust, result) => {
sql.query(
"UPDATE customers SET first_name = ? , last_name = ? , country_code = ? , mobile = ? , email = ? , created_user_id = ? , created_time = ? , updated_user_id = ? , updated_time = ? , is_active = ? , pw = ? WHERE id = ?",
[cust.first_name, cust.last_name, cust.country_code , cust.mobile , cust.email , cust.created_user_id, cust.created_time , cust.updated_user_id, cust.updated_time , cust.is_active , cust.pw ,id],
(err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found custloc with the id
result({ kind: "not_found" }, null);
return;
}
console.log("updated cust: ", { id: id, ...cust });
result(null, { id: id, ...cust });
}
);
};
custloc.remove = (id, result) => {
sql.query("DELETE FROM customers WHERE id = ?", id, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found custloc with the id
result({ kind: "not_found" }, null);
return;
}
console.log("deleted cust with id: ", id);
result(null, res);
});
};
custloc.removeAll = result => {
sql.query("DELETE FROM customers", (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log(`deleted ${res.affectedRows} custs`);
result(null, res);
});
};
module.exports = custloc;