helpers.js 1.3 KB

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