Source: competency/index.js

  1. /**
  2. * @module competency
  3. */
  4. const competencyRepo = require("../../repositories/competency");
  5. const cache = require("../cache");
  6. const _ = require('lodash');
  7. /**
  8. * Fetch all competencies. If cached,
  9. * return from cache, otherwise, fetch from
  10. * database and cache the values.
  11. * @return {Array} all competency objects
  12. */
  13. const fetchAll = async () => {
  14. if (cache.has("competencies")) {
  15. return cachedVal = cache.get("competencies");
  16. } else {
  17. const findResult = await competencyRepo.findAll();
  18. cache.set("competencies", findResult.rows);
  19. return findResult.rows;
  20. }
  21. };
  22. /**
  23. * Fetch competencies based on input keyword.
  24. * If competencies are cached, return from cache,
  25. * otherwise, fetch from database.
  26. * @param {String} keyword
  27. * @return {Array} matching competency objects
  28. */
  29. const fetchByKeyword = async (keyword) => {
  30. if (cache.has("competencies")) {
  31. const cachedVal = cache.get("competencies");
  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 competencyRepo.findByKeyword(keyword ? keyword : '');
  43. return findResult.rows;
  44. };
  45. /**
  46. * Fetch all competencies based on input parent id.
  47. * If competencies are cached, return from cache,
  48. * otherwise, fetch from database.
  49. * A parent of a competency refers to the higher level
  50. * grouping: 'categories'.
  51. * @param {Number} parentId
  52. * @return {Array} matching competency objects
  53. */
  54. const fetchAllByParent = async (parentId) => {
  55. if (cache.has("competencies")) {
  56. const cachedVal = cache.get("competencies");
  57. const matching = [];
  58. cachedVal.forEach(e => {
  59. if (e.parentId === parentId) {
  60. matching.push(e);
  61. }
  62. });
  63. return matching;
  64. }
  65. const findResult = await competencyRepo.findAllByParent(parentId);
  66. return findResult.rows;
  67. };
  68. /**
  69. * Fetch a competency object by id from database.
  70. * @param {Number} id
  71. * @return {Object} competency object
  72. */
  73. const fetchById = async (id) => {
  74. const findResult = await competencyRepo.findById(id);
  75. return findResult.rows[0];
  76. };
  77. module.exports = {
  78. fetchAll,
  79. fetchByKeyword,
  80. fetchAllByParent,
  81. fetchById,
  82. };