const express = require('express'); const path = require('path'); const RepositorySystem = require('../systems/RepositorySystem'); const Actions = require('../systems/ActionSystem'); class OneToOne { constructor(name, inceptor){ this.name = name; this.scheme = { auto_increment: 1, fields: [ { key: "name", type: "string", keyLength: 200 } ] }; this.repository = RepositorySystem.create(this.name, this.scheme); this.inceptor = inceptor; this.inceptorScheme = { fields: [ { key: this.name + "_id", type: "integer", fk: { "table": this.name, "key": "id" } } ] }; this.inceptorRepo = RepositorySystem.create(this.inceptor, this.inceptorScheme); this._init2(); } _init2() { Actions.on('model'+this.inceptor, (model) => { return this.repository.getPage(0,1000) .then((categories) => { return { ...model, [this.name]: { Filter: { type: "onetoone", options: categories.reduce((data,a) => {return {...data, [a.id]: a.name }}, {}), name: this.name, field: this.name + "_id", order: 50 } } } }) }); Actions.on('get'+this.inceptor, (product) => { if (!product[this.name + "_id"]) return product; return this.repository.raw().where('id', product[this.name+"_id"]) .then((items) => { product[this.name] = items[0]; delete product[this.name+"_id"]; return product; }); }); Actions.on('import'+this.inceptor, (dataset) => { return this.repository.getPage(0,1000).then((cats) => { let catNames = cats.reduce((w, a) => { w[a.name] = a.id; return w; },{}); let categories = dataset.reduce((acc, item) => { let categories = (item[this.name] || ''); if(categories && !acc.includes(categories))acc.push(categories); return acc; },[]); var filtered = categories.filter(function(value, index, arr){ return !catNames[value]; }); filtered = filtered.map((name) => {return {name}}) return this.repository.batchInsert(filtered) .then(() => this.repository.getPage(0,1000)) .then((cats) => { return cats.reduce((w, a) => { w[a.name] = a.id; return w; },{}); }) .then((names) => dataset.map((item) => { let categories = item[this.name]; if(categories)item[this.name + "_id"] = names[categories]; return item; })); }); }); } } module.exports = OneToOne;