Untitled
unknown
javascript
4 years ago
1.9 kB
7
Indexable
const db = require("../../db_knex");
const tables = require('consts/tables')
const attributeTable = tables.TABLA_ATTRB;
const attributeValueTable = tables.TABLA_ATTRB_VALOR;
const getItems = (whereParam) =>
  db(`${attributeTable} as ca`)
    .join(`${attributeValueTable} as cv`, "ca.id", "cv.id_atributo")
    .where(whereParam)
    .select(
      "ca.id as ID_attrb",
      "ca.nombre as attrb_name",
      "ca.habilitado as attrb_enable",
      "cv.id as ID_value",
      "cv.valor as attrb_value"
    );
const def = { "ca.eliminado": false, "cv.eliminado": false };
const getList = () => getItems(def);
const getSingle = (id) => getItems({ ...def, "ca.id": id });
const addTrx = async (trx, name, values, enable) => {
  const [id] = await trx(attributeTable).insert({
    nombre: name,
    habilitado: enable,
  });
  const insertValues = values.map((v) => ({ id_atributo: id, valor: v }));
  const inserts = await trx(attributeValueTable).insert(insertValues);
  console.log(`${inserts.length} new attributes values saved.`);
  return inserts;
};
const addAttribute = async (name, values, enable) => {
  try {
    return await db.transaction((trx) => addTrx(trx, name, values, enable));
  } catch (error) {
    console.error(error);
    return { error: "Se produjo un error en el alta" };
  }
};
const updateItem = (id, params, table) =>
  db(table).where({ id, eliminado: false }).update(params);
const modifyAttribute = (data, id, isValue) =>
  updateItem(id, data, isValue ? attributeValueTable : attributeTable);
const addValue = (valor, id) =>
  db(attributeValueTable).insert({ valor, id_atributo: id });
const remove = (id, isValue) =>
  updateItem(
    id,
    { eliminado: true },
    isValue ? attributeValueTable : attributeTable
  );
module.exports = {
  getList,
  getSingle,
  addAttribute,
  modifyAttribute,
  remove,
  addValue,
};
Editor is loading...