helpers.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const moment = require('moment');
  2. const {isPostgres} = require('./config');
  3. const {ref} = require('objection');
  4. module.exports = {
  5. /**
  6. * Takes an expression such as 30d and returns a moment object of that date in future
  7. *
  8. * Key Shorthand
  9. * ==================
  10. * years y
  11. * quarters Q
  12. * months M
  13. * weeks w
  14. * days d
  15. * hours h
  16. * minutes m
  17. * seconds s
  18. * milliseconds ms
  19. *
  20. * @param {String} expression
  21. * @returns {Object}
  22. */
  23. parseDatePeriod: function (expression) {
  24. let matches = expression.match(/^([0-9]+)(y|Q|M|w|d|h|m|s|ms)$/m);
  25. if (matches) {
  26. return moment().add(matches[1], matches[2]);
  27. }
  28. return null;
  29. },
  30. convertIntFieldsToBool: function (obj, fields) {
  31. fields.forEach(function (field) {
  32. if (typeof obj[field] !== 'undefined') {
  33. obj[field] = obj[field] === 1;
  34. }
  35. });
  36. return obj;
  37. },
  38. convertBoolFieldsToInt: function (obj, fields) {
  39. fields.forEach(function (field) {
  40. if (typeof obj[field] !== 'undefined') {
  41. obj[field] = obj[field] ? 1 : 0;
  42. }
  43. });
  44. return obj;
  45. },
  46. /**
  47. * Casts a column to json if using postgres
  48. *
  49. * @param {string} colName
  50. * @returns {string|Objection.ReferenceBuilder}
  51. */
  52. castJsonIfNeed: function (colName) {
  53. return isPostgres() ? ref(colName).castText() : colName;
  54. }
  55. };