join-sql-fragments.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var __defProp = Object.defineProperty;
  2. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  3. var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
  4. var __export = (target, all) => {
  5. __markAsModule(target);
  6. for (var name in all)
  7. __defProp(target, name, { get: all[name], enumerable: true });
  8. };
  9. var __publicField = (obj, key, value) => {
  10. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  11. return value;
  12. };
  13. __export(exports, {
  14. JoinSQLFragmentsError: () => JoinSQLFragmentsError,
  15. joinSQLFragments: () => joinSQLFragments
  16. });
  17. function doesNotWantLeadingSpace(str) {
  18. return /^[;,)]/.test(str);
  19. }
  20. function doesNotWantTrailingSpace(str) {
  21. return /\($/.test(str);
  22. }
  23. function singleSpaceJoinHelper(parts) {
  24. return parts.reduce(({ skipNextLeadingSpace, result }, part) => {
  25. if (skipNextLeadingSpace || doesNotWantLeadingSpace(part)) {
  26. result += part.trim();
  27. } else {
  28. result += ` ${part.trim()}`;
  29. }
  30. return {
  31. skipNextLeadingSpace: doesNotWantTrailingSpace(part),
  32. result
  33. };
  34. }, {
  35. skipNextLeadingSpace: true,
  36. result: ""
  37. }).result;
  38. }
  39. function joinSQLFragments(array) {
  40. if (array.length === 0)
  41. return "";
  42. const truthyArray = array.filter((x) => !!x);
  43. const flattenedArray = truthyArray.map((fragment) => {
  44. if (Array.isArray(fragment)) {
  45. return joinSQLFragments(fragment);
  46. }
  47. return fragment;
  48. });
  49. for (const fragment of flattenedArray) {
  50. if (fragment && typeof fragment !== "string") {
  51. throw new JoinSQLFragmentsError(flattenedArray, fragment, `Tried to construct a SQL string with a non-string, non-falsy fragment (${fragment}).`);
  52. }
  53. }
  54. const trimmedArray = flattenedArray.map((x) => x.trim());
  55. const nonEmptyStringArray = trimmedArray.filter((x) => x !== "");
  56. return singleSpaceJoinHelper(nonEmptyStringArray);
  57. }
  58. class JoinSQLFragmentsError extends TypeError {
  59. constructor(args, fragment, message) {
  60. super(message);
  61. __publicField(this, "args");
  62. __publicField(this, "fragment");
  63. this.args = args;
  64. this.fragment = fragment;
  65. this.name = "JoinSQLFragmentsError";
  66. }
  67. }
  68. //# sourceMappingURL=join-sql-fragments.js.map