CrudModule.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. const Module = require('./Module');
  2. const RepositorySystem = require('../systems/RepositorySystem');
  3. const RoutingSystem = require('../systems/RoutingSystem');
  4. const UserSystem = require('../systems/UserSystem');
  5. const Logger = require('../systems/LoggerSystem');
  6. const Actions = require('../systems/ActionSystem');
  7. const Filter = require('../modules/Filters/FilterService');
  8. const knex = require('../database/db')();
  9. let ModulesLoaded = [];
  10. const ItemBasicScheme = {
  11. fields: [
  12. {
  13. key: "createdAt",
  14. type: "timestamp",
  15. default: knex.fn.now()
  16. },
  17. {
  18. key: "updatedAt",
  19. type: "timestamp"
  20. },
  21. {
  22. key: "deleted",
  23. type: "boolean",
  24. default: 0,
  25. notNull: true
  26. }
  27. ]
  28. };
  29. RoutingSystem.loadRoutes([{
  30. type: 'custom',
  31. method: 'get',
  32. endpoint: '/CrudModules',
  33. customFn: (req, res) => {
  34. res.send(ModulesLoaded);
  35. }
  36. }]);
  37. class CrudModule extends Module {
  38. // Roles [ CREATE , READ , UPDATE , DELETE , READ ALL]
  39. constructor(prefix = '/', roles = [1,1,3,4,1], name = 'General', icon = '', Middlewares = []){
  40. super();
  41. this.routerPrefix = prefix;
  42. this.roles = roles;
  43. this.name = name;
  44. this.Middlewares = Middlewares;
  45. this.Model = {
  46. id: {
  47. type: 'Disabled'
  48. }
  49. };
  50. ModulesLoaded.push({
  51. Name: name,
  52. Route: prefix,
  53. Icon: icon
  54. });
  55. this._initCrud();
  56. }
  57. _initCrud() {
  58. let crudroutes = [
  59. {
  60. type: 'custom',
  61. method: 'get',
  62. endpoint: '/Model',
  63. customFn: this.getModel.bind(this)
  64. },
  65. {
  66. type: 'custom',
  67. method: 'post',
  68. endpoint: '/import',
  69. customFn: this.import.bind(this)
  70. },
  71. {
  72. type: 'custom',
  73. method: 'get',
  74. endpoint: '/search/:search',
  75. customFn: (req, res) => {
  76. this.search(req, res);
  77. }
  78. },
  79. {
  80. type: 'custom',
  81. method: 'get',
  82. endpoint: '/',
  83. customFn: this.getPage.bind(this)
  84. },
  85. {
  86. type: 'custom',
  87. method: 'get',
  88. endpoint: '/count',
  89. customFn: this.count.bind(this)
  90. },
  91. {
  92. type: 'custom',
  93. method: 'get',
  94. endpoint: '/:id',
  95. customFn: this.get.bind(this)
  96. },
  97. {
  98. type: 'custom',
  99. method: 'post',
  100. endpoint: '/',
  101. customFn: this.post.bind(this)
  102. },
  103. {
  104. type: 'custom',
  105. method: 'put',
  106. endpoint: '/:id',
  107. customFn: this.put.bind(this)
  108. },
  109. {
  110. type: 'custom',
  111. method: 'delete',
  112. endpoint: '/:id',
  113. customFn: this.del.bind(this)
  114. }
  115. ];
  116. RoutingSystem.loadRoutes(crudroutes, this.router, this.routerPrefix, this.Middlewares);
  117. Actions.on('post' + this.name, (item) => {
  118. delete item.createdAt;
  119. item.updatedAt = knex.fn.now();
  120. return item;
  121. });
  122. }
  123. getModel(req, res) {
  124. let ModelDTO = {};
  125. return this._repository.columns().then((value) => {
  126. for(var i in value) {
  127. ModelDTO[i] = value[i];
  128. }
  129. }).then(() => Actions.emit('model'+this.name, this.Model, req, res))
  130. .then((model) => {
  131. for(var i in model) {
  132. ModelDTO[i] = { ...ModelDTO[i], ...model[i] };
  133. }
  134. res.send(ModelDTO);
  135. });
  136. }
  137. import(req, res) {
  138. let data = req.body;
  139. if(!data.rows || !data.cols) {
  140. res.status(400);
  141. res.send("No rows || no cols");
  142. return;
  143. }
  144. let dict = data.cols.reduce((initial, item) => (initial[item.key] = item.name) && initial, {})
  145. let dataset = data.rows.map((row) => {
  146. return row.reduce((initial, field, indx) => {
  147. (initial[dict[indx]] = field)
  148. return initial;
  149. }, {});
  150. });
  151. Actions.emit("import" + this.name, dataset, req, res)
  152. .then((batch) => Promise.all(batch.map((i) => this.clearObject(i))))
  153. .then((batch) => {
  154. console.log("BATCH" , batch[0]);
  155. this._repository.batchInsert(batch)
  156. })
  157. .then(() => res.sendStatus(200))
  158. .catch((e) => {
  159. console.log(e);
  160. console.log("ERROR");
  161. res.sendStatus(500)
  162. });
  163. }
  164. setRepo(repo) {
  165. this._repository = repo;
  166. let name = this._repository.table;
  167. RepositorySystem.create(name, ItemBasicScheme);
  168. }
  169. search(req, res) {
  170. let searchParam = req.params.search;
  171. Filter.parseFilters(
  172. this.repository.raw(),
  173. req.filters
  174. ).where('name', 'like', '%'+searchParam+'%')
  175. .then((data) => Actions.emit('get' + this.name, data, req, res))
  176. .then((data) => res.send(data));
  177. }
  178. getPage(req, res) {
  179. UserSystem.role(req, res, this.roles[4]);
  180. let page = req.query.page;
  181. Filter.parseFilters(
  182. this._repository.getPage(page, req.query.perPage),
  183. req.filters
  184. )
  185. .then((data) => Actions.emitArray('get'+this.name, data, req, res))
  186. .then((data) => res.send(data || []))
  187. .catch((e) => {
  188. Logger.error(e);
  189. return res.sendStatus(500);
  190. });
  191. }
  192. get(req, res) {
  193. UserSystem.role(req, res, this.roles[1]);
  194. let id = req.params.id;
  195. this._repository.get('id', id)
  196. .then((data) => {
  197. if(!data.length) throw 404;
  198. return Actions.emit('get'+this.name, data[0], req, res);
  199. })
  200. .then((data) => res.send(data))
  201. .catch((e) => {
  202. if(e === 404) {
  203. return res.sendStatus(404);
  204. }
  205. Logger.error(e);
  206. });
  207. }
  208. count(req, res) {
  209. UserSystem.role(req, res, this.roles[4]);
  210. Filter.parseFilters(this._repository.count(), req.filters)
  211. .then((data) => {
  212. res.send(data);
  213. })
  214. .catch((e) => {
  215. if(e === 404) {
  216. return res.sendStatus(404);
  217. }
  218. Logger.error(e);
  219. });
  220. }
  221. post(req, res) {
  222. UserSystem.role(req, res, this.roles[0]);
  223. let body = req.body;
  224. Actions.emit('post'+ this.name, body, req, res)
  225. .then((data) => {
  226. return this.clearObject(data);
  227. })
  228. .then((data) => {
  229. return this._repository.insert(data)
  230. })
  231. .then((data) => {
  232. res.sendStatus(200);
  233. })
  234. .catch((e) => {
  235. res.sendStatus(500);
  236. Logger.error(e);
  237. });
  238. }
  239. put(req, res) {
  240. UserSystem.role(req, res, this.roles[2]);
  241. let id = req.params.id;
  242. let body = {...req.body};
  243. Actions.emit('post'+ this.name, body, req, res)
  244. .then((data) => {
  245. return this.clearObject(data)
  246. })
  247. .then((data) => {
  248. return this._repository.update(id, body)
  249. })
  250. .then((data) => {
  251. if(!data) throw 404;
  252. res.status(200).send(''+data);
  253. })
  254. .catch((e) => {
  255. if(e === 404) {
  256. Logger.log("Not found");
  257. return res.sendStatus(404);
  258. }
  259. Logger.error(e);
  260. });
  261. }
  262. del(req, res) {
  263. UserSystem.role(req, res, this.roles[3]);
  264. let id = req.params.id;
  265. this._repository.delete(id)
  266. .then((data) => {
  267. if(!data.length) throw 404;
  268. res.send(data[0]);
  269. })
  270. .catch((e) => {
  271. if(e === 404) {
  272. return res.sendStatus(404);
  273. }
  274. Logger.error(e);
  275. });
  276. }
  277. clearObject(object) {
  278. return this._repository.columns().then((values) => {
  279. let fields = Object.keys(values);
  280. for(var i in object) {
  281. if(!fields.includes(i)) {
  282. delete object[i];
  283. }
  284. }
  285. return object;
  286. });
  287. }
  288. }
  289. module.exports = CrudModule;