casing.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { entityKind } from "./entity.js";
  2. import { Table } from "./table.js";
  3. function toSnakeCase(input) {
  4. const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  5. return words.map((word) => word.toLowerCase()).join("_");
  6. }
  7. function toCamelCase(input) {
  8. const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  9. return words.reduce((acc, word, i) => {
  10. const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
  11. return acc + formattedWord;
  12. }, "");
  13. }
  14. function noopCase(input) {
  15. return input;
  16. }
  17. class CasingCache {
  18. static [entityKind] = "CasingCache";
  19. /** @internal */
  20. cache = {};
  21. cachedTables = {};
  22. convert;
  23. constructor(casing) {
  24. this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
  25. }
  26. getColumnCasing(column) {
  27. if (!column.keyAsName) return column.name;
  28. const schema = column.table[Table.Symbol.Schema] ?? "public";
  29. const tableName = column.table[Table.Symbol.OriginalName];
  30. const key = `${schema}.${tableName}.${column.name}`;
  31. if (!this.cache[key]) {
  32. this.cacheTable(column.table);
  33. }
  34. return this.cache[key];
  35. }
  36. cacheTable(table) {
  37. const schema = table[Table.Symbol.Schema] ?? "public";
  38. const tableName = table[Table.Symbol.OriginalName];
  39. const tableKey = `${schema}.${tableName}`;
  40. if (!this.cachedTables[tableKey]) {
  41. for (const column of Object.values(table[Table.Symbol.Columns])) {
  42. const columnKey = `${tableKey}.${column.name}`;
  43. this.cache[columnKey] = this.convert(column.name);
  44. }
  45. this.cachedTables[tableKey] = true;
  46. }
  47. }
  48. clearCache() {
  49. this.cache = {};
  50. this.cachedTables = {};
  51. }
  52. }
  53. export {
  54. CasingCache,
  55. toCamelCase,
  56. toSnakeCase
  57. };
  58. //# sourceMappingURL=casing.js.map