Source: capability/index.js

  1. /**
  2. * @module capability
  3. */
  4. const capabilityRepo = require("../../repositories/capability");
  5. const cache = require("../cache");
  6. const _ = require('lodash');
  7. /**
  8. * Fetch all capabilities. If cached,
  9. * return from cache, otherwise, fetch from
  10. * database and cache the values.
  11. * @return {Array} all capability objects
  12. */
  13. const fetchAll = async () => {
  14. if (cache.has("capabilities")) {
  15. return cache.get("capabilities");
  16. } else {
  17. const findResult = await capabilityRepo.findAll();
  18. cache.set("capabilities", findResult.rows);
  19. return findResult.rows;
  20. }
  21. };
  22. /**
  23. * Fetch capabilities based on input keyword.
  24. * If capabilities are cached, return from cache,
  25. * otherwise, fetch from database.
  26. * @param {String} keyword
  27. * @return {Array} matching capability objects
  28. */
  29. const fetchByKeyword = async (keyword) => {
  30. if (cache.has("capabilities")) {
  31. const cachedVal = cache.get("capabilities");
  32. const safeKey = _.escapeRegExp(keyword);
  33. const regex = RegExp(safeKey ? safeKey : '', 'i');
  34. const matching = [];
  35. cachedVal.forEach(e => {
  36. if (regex.test(e.title)) {
  37. matching.push(e);
  38. }
  39. });
  40. return matching;
  41. }
  42. const findResult = await capabilityRepo.findByKeyword(keyword ? keyword : '');
  43. return findResult.rows;
  44. };
  45. /**
  46. * Fetch a capability object by id from database.
  47. * @param {Number} id
  48. * @return {Object} capability object
  49. */
  50. const fetchById = async (id) => {
  51. const findResult = await capabilityRepo.findById(id);
  52. return findResult.rows[0];
  53. };
  54. module.exports = {
  55. fetchAll,
  56. fetchByKeyword,
  57. fetchById,
  58. };