@loomcore/api 0.0.59 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +50 -0
  3. package/dist/__tests__/common-test.utils.d.ts +29 -60
  4. package/dist/__tests__/common-test.utils.js +88 -166
  5. package/dist/__tests__/index.d.ts +6 -0
  6. package/dist/__tests__/index.js +6 -0
  7. package/dist/__tests__/models/category.model.d.ts +8 -0
  8. package/dist/__tests__/models/category.model.js +6 -0
  9. package/dist/__tests__/models/mongo-test-entity.model.d.ts +11 -0
  10. package/dist/__tests__/models/mongo-test-entity.model.js +13 -0
  11. package/dist/__tests__/models/product.model.d.ts +17 -0
  12. package/dist/__tests__/models/product.model.js +10 -0
  13. package/dist/__tests__/models/test-entity.model.d.ts +11 -0
  14. package/dist/__tests__/models/test-entity.model.js +10 -0
  15. package/dist/__tests__/models/test-item.model.d.ts +12 -0
  16. package/dist/__tests__/models/test-item.model.js +9 -0
  17. package/dist/__tests__/mongo-db.test-database.d.ts +15 -0
  18. package/dist/__tests__/mongo-db.test-database.js +74 -0
  19. package/dist/__tests__/postgres-test-migrations/001-create-test-entities-table.migration.d.ts +11 -0
  20. package/dist/__tests__/postgres-test-migrations/001-create-test-entities-table.migration.js +59 -0
  21. package/dist/__tests__/postgres-test-migrations/002-create-categories-table.migration.d.ts +11 -0
  22. package/dist/__tests__/postgres-test-migrations/002-create-categories-table.migration.js +52 -0
  23. package/dist/__tests__/postgres-test-migrations/003-create-products-table.migration.d.ts +11 -0
  24. package/dist/__tests__/postgres-test-migrations/003-create-products-table.migration.js +62 -0
  25. package/dist/__tests__/postgres-test-migrations/004-create-test-users-table.migration.d.ts +11 -0
  26. package/dist/__tests__/postgres-test-migrations/004-create-test-users-table.migration.js +66 -0
  27. package/dist/__tests__/postgres-test-migrations/005-create-test-items-table.migration.d.ts +11 -0
  28. package/dist/__tests__/postgres-test-migrations/005-create-test-items-table.migration.js +50 -0
  29. package/dist/__tests__/postgres-test-migrations/run-test-migrations.d.ts +2 -0
  30. package/dist/__tests__/postgres-test-migrations/run-test-migrations.js +22 -0
  31. package/dist/__tests__/postgres.test-database.d.ts +13 -0
  32. package/dist/__tests__/postgres.test-database.js +85 -0
  33. package/dist/__tests__/test-database.interface.d.ts +7 -0
  34. package/dist/__tests__/test-express-app.d.ts +9 -7
  35. package/dist/__tests__/test-express-app.js +38 -48
  36. package/dist/__tests__/test-mongo-db.d.ts +14 -0
  37. package/dist/__tests__/test-mongo-db.js +81 -0
  38. package/dist/__tests__/test-objects.d.ts +23 -0
  39. package/dist/__tests__/test-objects.js +45 -0
  40. package/dist/__tests__/test-user.d.ts +3 -0
  41. package/dist/__tests__/test-user.js +16 -0
  42. package/dist/config/base-api-config.d.ts +2 -2
  43. package/dist/config/base-api-config.js +2 -2
  44. package/dist/controllers/api.controller.d.ts +1 -5
  45. package/dist/controllers/api.controller.js +4 -11
  46. package/dist/controllers/auth.controller.d.ts +2 -2
  47. package/dist/controllers/auth.controller.js +4 -5
  48. package/dist/controllers/organizations.controller.d.ts +2 -2
  49. package/dist/controllers/organizations.controller.js +4 -4
  50. package/dist/controllers/users.controller.d.ts +2 -2
  51. package/dist/controllers/users.controller.js +2 -2
  52. package/dist/databases/index.d.ts +1 -0
  53. package/dist/databases/index.js +1 -0
  54. package/dist/databases/models/constants.d.ts +1 -0
  55. package/dist/databases/models/constants.js +1 -0
  56. package/dist/databases/models/database.d.ts +3 -0
  57. package/dist/databases/models/database.interface.d.ts +28 -0
  58. package/dist/databases/models/delete-result.d.ts +5 -0
  59. package/dist/databases/models/delete-result.js +8 -0
  60. package/dist/databases/models/index.d.ts +5 -0
  61. package/dist/databases/models/index.js +5 -0
  62. package/dist/databases/models/update-result.d.ts +5 -0
  63. package/dist/databases/models/update-result.js +8 -0
  64. package/dist/databases/mongo-db/commands/batch-update.command.d.ts +3 -0
  65. package/dist/databases/mongo-db/commands/batch-update.command.js +41 -0
  66. package/dist/databases/mongo-db/commands/create-many.command.d.ts +5 -0
  67. package/dist/databases/mongo-db/commands/create-many.command.js +17 -0
  68. package/dist/databases/mongo-db/commands/create.command.d.ts +5 -0
  69. package/dist/databases/mongo-db/commands/create.command.js +17 -0
  70. package/dist/databases/mongo-db/commands/delete-by-id.command.d.ts +3 -0
  71. package/dist/databases/mongo-db/commands/delete-by-id.command.js +9 -0
  72. package/dist/databases/mongo-db/commands/delete-many.command.d.ts +4 -0
  73. package/dist/databases/mongo-db/commands/delete-many.command.js +9 -0
  74. package/dist/databases/mongo-db/commands/full-updateby-id.command.d.ts +3 -0
  75. package/dist/databases/mongo-db/commands/full-updateby-id.command.js +21 -0
  76. package/dist/databases/mongo-db/commands/index.d.ts +8 -0
  77. package/dist/databases/mongo-db/commands/index.js +8 -0
  78. package/dist/databases/mongo-db/commands/mongo-batch-update.command.d.ts +4 -0
  79. package/dist/databases/mongo-db/commands/mongo-batch-update.command.js +41 -0
  80. package/dist/databases/mongo-db/commands/mongo-create-many.command.d.ts +5 -0
  81. package/dist/databases/mongo-db/commands/mongo-create-many.command.js +17 -0
  82. package/dist/databases/mongo-db/commands/mongo-create.command.d.ts +5 -0
  83. package/dist/databases/mongo-db/commands/mongo-create.command.js +17 -0
  84. package/dist/databases/mongo-db/commands/mongo-delete-by-id.command.d.ts +3 -0
  85. package/dist/databases/mongo-db/commands/mongo-delete-by-id.command.js +14 -0
  86. package/dist/databases/mongo-db/commands/mongo-delete-many.command.d.ts +4 -0
  87. package/dist/databases/mongo-db/commands/mongo-delete-many.command.js +9 -0
  88. package/dist/databases/mongo-db/commands/mongo-full-updateby-id.command.d.ts +3 -0
  89. package/dist/databases/mongo-db/commands/mongo-full-updateby-id.command.js +25 -0
  90. package/dist/databases/mongo-db/commands/mongo-partial-update-by-id.command.d.ts +3 -0
  91. package/dist/databases/mongo-db/commands/mongo-partial-update-by-id.command.js +25 -0
  92. package/dist/databases/mongo-db/commands/mongo-update.command.d.ts +4 -0
  93. package/dist/databases/mongo-db/commands/mongo-update.command.js +19 -0
  94. package/dist/databases/mongo-db/commands/partial-update-by-id.command.d.ts +3 -0
  95. package/dist/databases/mongo-db/commands/partial-update-by-id.command.js +21 -0
  96. package/dist/databases/mongo-db/commands/update.command.d.ts +4 -0
  97. package/dist/databases/mongo-db/commands/update.command.js +19 -0
  98. package/dist/databases/mongo-db/index.d.ts +4 -0
  99. package/dist/databases/mongo-db/index.js +4 -0
  100. package/dist/databases/mongo-db/models/no-sql-pipeline.d.ts +15 -0
  101. package/dist/databases/mongo-db/models/no-sql-pipeline.interface.d.ts +11 -0
  102. package/dist/databases/mongo-db/models/no-sql-pipeline.js +43 -0
  103. package/dist/databases/mongo-db/mongo-db.database.d.ts +32 -0
  104. package/dist/databases/mongo-db/mongo-db.database.js +65 -0
  105. package/dist/databases/mongo-db/queries/find-one.query.d.ts +3 -0
  106. package/dist/databases/mongo-db/queries/find-one.query.js +9 -0
  107. package/dist/databases/mongo-db/queries/find.query.d.ts +3 -0
  108. package/dist/databases/mongo-db/queries/find.query.js +9 -0
  109. package/dist/databases/mongo-db/queries/get-all.query.d.ts +3 -0
  110. package/dist/databases/mongo-db/queries/get-all.query.js +17 -0
  111. package/dist/databases/mongo-db/queries/get-by-id.query.d.ts +3 -0
  112. package/dist/databases/mongo-db/queries/get-by-id.query.js +20 -0
  113. package/dist/databases/mongo-db/queries/get-count.query.d.ts +2 -0
  114. package/dist/databases/mongo-db/queries/get-count.query.js +5 -0
  115. package/dist/databases/mongo-db/queries/get.query.d.ts +4 -0
  116. package/dist/databases/mongo-db/queries/get.query.js +14 -0
  117. package/dist/databases/mongo-db/queries/index.d.ts +6 -0
  118. package/dist/databases/mongo-db/queries/index.js +6 -0
  119. package/dist/databases/mongo-db/queries/mongo-find-one.query.d.ts +3 -0
  120. package/dist/databases/mongo-db/queries/mongo-find-one.query.js +9 -0
  121. package/dist/databases/mongo-db/queries/mongo-find.query.d.ts +3 -0
  122. package/dist/databases/mongo-db/queries/mongo-find.query.js +9 -0
  123. package/dist/databases/mongo-db/queries/mongo-get-all.query.d.ts +3 -0
  124. package/dist/databases/mongo-db/queries/mongo-get-all.query.js +17 -0
  125. package/dist/databases/mongo-db/queries/mongo-get-by-id.query.d.ts +4 -0
  126. package/dist/databases/mongo-db/queries/mongo-get-by-id.query.js +17 -0
  127. package/dist/databases/mongo-db/queries/mongo-get-count.query.d.ts +2 -0
  128. package/dist/databases/mongo-db/queries/mongo-get-count.query.js +5 -0
  129. package/dist/databases/mongo-db/queries/mongo-get.query.d.ts +4 -0
  130. package/dist/databases/mongo-db/queries/mongo-get.query.js +14 -0
  131. package/dist/databases/mongo-db/utils/build-find-options.util.d.ts +3 -0
  132. package/dist/databases/mongo-db/utils/build-find-options.util.js +15 -0
  133. package/dist/databases/mongo-db/utils/build-no-sql-match.util.d.ts +3 -0
  134. package/dist/databases/mongo-db/utils/build-no-sql-match.util.js +59 -0
  135. package/dist/databases/mongo-db/utils/convert-object-ids-to-strings.util.d.ts +1 -0
  136. package/dist/databases/mongo-db/utils/convert-object-ids-to-strings.util.js +32 -0
  137. package/dist/databases/mongo-db/utils/convert-operations-to-pipeline.util.d.ts +3 -0
  138. package/dist/databases/mongo-db/utils/convert-operations-to-pipeline.util.js +68 -0
  139. package/dist/databases/mongo-db/utils/convert-query-options-to-pipeline.util.d.ts +3 -0
  140. package/dist/databases/mongo-db/utils/convert-query-options-to-pipeline.util.js +31 -0
  141. package/dist/databases/mongo-db/utils/convert-strings-to-object-ids.util.d.ts +3 -0
  142. package/dist/databases/mongo-db/utils/convert-strings-to-object-ids.util.js +72 -0
  143. package/dist/databases/mongo-db/utils/index.d.ts +7 -0
  144. package/dist/databases/mongo-db/utils/index.js +7 -0
  145. package/dist/databases/operations/join.operation.d.ts +7 -0
  146. package/dist/databases/operations/join.operation.js +12 -0
  147. package/dist/databases/operations/operation.d.ts +2 -0
  148. package/dist/databases/postgres/commands/postgres-batch-update.command.d.ts +4 -0
  149. package/dist/databases/postgres/commands/postgres-batch-update.command.js +56 -0
  150. package/dist/databases/postgres/commands/postgres-create-many.command.d.ts +6 -0
  151. package/dist/databases/postgres/commands/postgres-create-many.command.js +63 -0
  152. package/dist/databases/postgres/commands/postgres-create.command.d.ts +6 -0
  153. package/dist/databases/postgres/commands/postgres-create.command.js +29 -0
  154. package/dist/databases/postgres/commands/postgres-delete-by-id.command.d.ts +3 -0
  155. package/dist/databases/postgres/commands/postgres-delete-by-id.command.js +6 -0
  156. package/dist/databases/postgres/commands/postgres-delete-many.command.d.ts +4 -0
  157. package/dist/databases/postgres/commands/postgres-delete-many.command.js +13 -0
  158. package/dist/databases/postgres/commands/postgres-full-update-by-id.command.d.ts +4 -0
  159. package/dist/databases/postgres/commands/postgres-full-update-by-id.command.js +72 -0
  160. package/dist/databases/postgres/commands/postgres-partial-update-by-id.command.d.ts +4 -0
  161. package/dist/databases/postgres/commands/postgres-partial-update-by-id.command.js +42 -0
  162. package/dist/databases/postgres/commands/postgres-update.command.d.ts +5 -0
  163. package/dist/databases/postgres/commands/postgres-update.command.js +48 -0
  164. package/dist/databases/postgres/migrations/001-create-migrations-table.migration.d.ts +11 -0
  165. package/dist/databases/postgres/migrations/001-create-migrations-table.migration.js +52 -0
  166. package/dist/databases/postgres/migrations/002-create-organizations-table.migration.d.ts +11 -0
  167. package/dist/databases/postgres/migrations/002-create-organizations-table.migration.js +55 -0
  168. package/dist/databases/postgres/migrations/003-create-users-table.migration.d.ts +11 -0
  169. package/dist/databases/postgres/migrations/003-create-users-table.migration.js +65 -0
  170. package/dist/databases/postgres/migrations/004-create-refresh-token-table.migration.d.ts +11 -0
  171. package/dist/databases/postgres/migrations/004-create-refresh-token-table.migration.js +57 -0
  172. package/dist/databases/postgres/migrations/index.d.ts +3 -0
  173. package/dist/databases/postgres/migrations/index.js +3 -0
  174. package/dist/databases/postgres/migrations/migration.d.ts +6 -0
  175. package/dist/databases/postgres/migrations/migration.interface.d.ts +6 -0
  176. package/dist/databases/postgres/migrations/migration.interface.js +1 -0
  177. package/dist/databases/postgres/migrations/migration.js +14 -0
  178. package/dist/databases/postgres/migrations/runMigrations.d.ts +2 -0
  179. package/dist/databases/postgres/migrations/runMigrations.js +20 -0
  180. package/dist/databases/postgres/migrations/setup-for-auth.migration.d.ts +2 -0
  181. package/dist/databases/postgres/migrations/setup-for-auth.migration.js +18 -0
  182. package/dist/databases/postgres/migrations/setup-for-multitenant.migration.d.ts +2 -0
  183. package/dist/databases/postgres/migrations/setup-for-multitenant.migration.js +16 -0
  184. package/dist/databases/postgres/postgres.database.d.ts +31 -0
  185. package/dist/databases/postgres/postgres.database.js +69 -0
  186. package/dist/databases/postgres/queries/postgres-find-one.query.d.ts +3 -0
  187. package/dist/databases/postgres/queries/postgres-find-one.query.js +13 -0
  188. package/dist/databases/postgres/queries/postgres-find.query.d.ts +3 -0
  189. package/dist/databases/postgres/queries/postgres-find.query.js +11 -0
  190. package/dist/databases/postgres/queries/postgres-get-all.query.d.ts +3 -0
  191. package/dist/databases/postgres/queries/postgres-get-all.query.js +14 -0
  192. package/dist/databases/postgres/queries/postgres-get-by-id.query.d.ts +4 -0
  193. package/dist/databases/postgres/queries/postgres-get-by-id.query.js +26 -0
  194. package/dist/databases/postgres/queries/postgres-get-count.query.d.ts +2 -0
  195. package/dist/databases/postgres/queries/postgres-get-count.query.js +4 -0
  196. package/dist/databases/postgres/queries/postgres-get.query.d.ts +4 -0
  197. package/dist/databases/postgres/queries/postgres-get.query.js +26 -0
  198. package/dist/databases/postgres/utils/build-count-query.d.ts +3 -0
  199. package/dist/databases/postgres/utils/build-count-query.js +7 -0
  200. package/dist/databases/postgres/utils/build-join-clauses.d.ts +2 -0
  201. package/dist/databases/postgres/utils/build-join-clauses.js +12 -0
  202. package/dist/databases/postgres/utils/build-order-by-clause.d.ts +2 -0
  203. package/dist/databases/postgres/utils/build-order-by-clause.js +8 -0
  204. package/dist/databases/postgres/utils/build-pagination-clause.d.ts +2 -0
  205. package/dist/databases/postgres/utils/build-pagination-clause.js +9 -0
  206. package/dist/databases/postgres/utils/build-select-clause.d.ts +3 -0
  207. package/dist/databases/postgres/utils/build-select-clause.js +28 -0
  208. package/dist/databases/postgres/utils/build-where-clause.d.ts +5 -0
  209. package/dist/databases/postgres/utils/build-where-clause.js +50 -0
  210. package/dist/databases/postgres/utils/columns-and-values-from-entity.d.ts +5 -0
  211. package/dist/databases/postgres/utils/columns-and-values-from-entity.js +9 -0
  212. package/dist/databases/postgres/utils/convert-null-to-undefined.util.d.ts +2 -0
  213. package/dist/databases/postgres/utils/convert-null-to-undefined.util.js +70 -0
  214. package/dist/databases/postgres/utils/transform-join-results.d.ts +2 -0
  215. package/dist/databases/postgres/utils/transform-join-results.js +33 -0
  216. package/dist/databases/utils/database-to-idatabase.util.d.ts +3 -0
  217. package/dist/databases/utils/database-to-idatabase.util.js +14 -0
  218. package/dist/databases/utils/get-property-schema.util.d.ts +2 -0
  219. package/dist/databases/utils/get-property-schema.util.js +15 -0
  220. package/dist/databases/utils/index.d.ts +1 -0
  221. package/dist/databases/utils/index.js +1 -0
  222. package/dist/models/base-api-config.interface.d.ts +3 -2
  223. package/dist/models/index.d.ts +1 -1
  224. package/dist/models/index.js +1 -1
  225. package/dist/models/refresh-token.d.ts +9 -0
  226. package/dist/models/refresh-token.js +2 -0
  227. package/dist/models/refresh-token.model.d.ts +18 -0
  228. package/dist/models/refresh-token.model.js +13 -0
  229. package/dist/models/refresh-token.spec.d.ts +1 -0
  230. package/dist/models/refresh-token.spec.js +12 -0
  231. package/dist/services/auth.service.d.ts +11 -18
  232. package/dist/services/auth.service.js +29 -50
  233. package/dist/services/generic-api-service/generic-api-service.interface.d.ts +29 -0
  234. package/dist/services/generic-api-service/generic-api-service.interface.js +1 -0
  235. package/dist/services/generic-api-service/generic-api.service.d.ts +37 -0
  236. package/dist/services/generic-api-service/generic-api.service.js +178 -0
  237. package/dist/services/index.d.ts +2 -2
  238. package/dist/services/index.js +2 -2
  239. package/dist/services/multi-tenant-api.service.d.ts +9 -6
  240. package/dist/services/multi-tenant-api.service.js +10 -18
  241. package/dist/services/organization.service.d.ts +5 -5
  242. package/dist/services/organization.service.js +9 -6
  243. package/dist/services/password-reset-token.service.d.ts +3 -3
  244. package/dist/services/password-reset-token.service.js +5 -5
  245. package/dist/services/tenant-query-decorator.d.ts +1 -1
  246. package/dist/services/tenant-query-decorator.js +1 -1
  247. package/dist/services/user.service.d.ts +4 -6
  248. package/dist/services/user.service.js +4 -10
  249. package/dist/services/utils/audit-for-create.util.d.ts +2 -0
  250. package/dist/services/utils/audit-for-create.util.js +9 -0
  251. package/dist/services/utils/audit-for-update.util.d.ts +2 -0
  252. package/dist/services/utils/audit-for-update.util.js +7 -0
  253. package/dist/services/utils/strip-sender-provided-system-properties.util.d.ts +2 -0
  254. package/dist/services/utils/strip-sender-provided-system-properties.util.js +15 -0
  255. package/dist/tsconfig.tsbuildinfo +1 -0
  256. package/dist/utils/api.utils.js +2 -1
  257. package/dist/utils/index.d.ts +0 -1
  258. package/dist/utils/index.js +0 -1
  259. package/dist/utils/sql.db.utils.d.ts +14 -0
  260. package/dist/utils/sql.db.utils.js +94 -0
  261. package/package.json +4 -2
  262. package/dist/services/generic-api-service.interface.d.ts +0 -27
  263. package/dist/services/generic-api.service.d.ts +0 -50
  264. package/dist/services/generic-api.service.js +0 -424
  265. package/dist/utils/db.utils.d.ts +0 -27
  266. package/dist/utils/db.utils.js +0 -318
  267. /package/dist/{controllers/api-controller.utils.d.ts → __tests__/test-database.interface.js} +0 -0
  268. /package/dist/{controllers/api-controller.utils.js → databases/models/database.interface.js} +0 -0
  269. /package/dist/{models/types/index.d.ts → databases/models/database.js} +0 -0
  270. /package/dist/{models/types/index.js → databases/mongo-db/models/no-sql-pipeline.interface.js} +0 -0
  271. /package/dist/{services/generic-api-service.interface.js → databases/operations/operation.js} +0 -0
@@ -0,0 +1,13 @@
1
+ import { buildWhereClause } from '../utils/build-where-clause.js';
2
+ import { DeleteResult } from "../../models/delete-result.js";
3
+ export async function deleteMany(client, queryObject, pluralResourceName) {
4
+ try {
5
+ const { whereClause, values } = buildWhereClause(queryObject);
6
+ const query = `DELETE FROM "${pluralResourceName}" ${whereClause}`;
7
+ const result = await client.query(query, values);
8
+ return new DeleteResult(true, result.rowCount || 0);
9
+ }
10
+ catch (error) {
11
+ return new DeleteResult(false, 0);
12
+ }
13
+ }
@@ -0,0 +1,4 @@
1
+ import { Client } from 'pg';
2
+ import { Operation } from "../../operations/operation.js";
3
+ import { IEntity } from '@loomcore/common/models';
4
+ export declare function fullUpdateById<T extends IEntity>(client: Client, operations: Operation[], id: string, entity: Partial<T>, pluralResourceName: string): Promise<T>;
@@ -0,0 +1,72 @@
1
+ import { BadRequestError, IdNotFoundError } from "../../../errors/index.js";
2
+ import { buildJoinClauses } from '../utils/build-join-clauses.js';
3
+ export async function fullUpdateById(client, operations, id, entity, pluralResourceName) {
4
+ try {
5
+ const tableColumns = await client.query(`
6
+ SELECT column_name, column_default
7
+ FROM information_schema.columns
8
+ WHERE table_schema = current_schema()
9
+ AND table_name = $1
10
+ ORDER BY ordinal_position
11
+ `, [pluralResourceName]);
12
+ if (tableColumns.rows.length === 0) {
13
+ throw new BadRequestError(`Unable to resolve columns for ${pluralResourceName}`);
14
+ }
15
+ const preservedColumns = new Set(['_id', '_created', '_createdBy']);
16
+ const entityRecord = entity;
17
+ const updateColumns = [];
18
+ const updateValues = [];
19
+ let paramIndex = 1;
20
+ for (const column of tableColumns.rows) {
21
+ const columnName = column.column_name;
22
+ if (preservedColumns.has(columnName)) {
23
+ continue;
24
+ }
25
+ if (columnName in entityRecord && entityRecord[columnName] !== undefined) {
26
+ updateColumns.push(`"${columnName}" = $${paramIndex}`);
27
+ updateValues.push(entityRecord[columnName]);
28
+ paramIndex++;
29
+ }
30
+ else if (column.column_default !== null) {
31
+ updateColumns.push(`"${columnName}" = DEFAULT`);
32
+ }
33
+ else {
34
+ updateColumns.push(`"${columnName}" = $${paramIndex}`);
35
+ updateValues.push(null);
36
+ paramIndex++;
37
+ }
38
+ }
39
+ if (updateColumns.length === 0) {
40
+ throw new BadRequestError('Cannot perform full update with no fields to update');
41
+ }
42
+ const setClause = updateColumns.join(', ');
43
+ const query = `
44
+ UPDATE "${pluralResourceName}"
45
+ SET ${setClause}
46
+ WHERE "_id" = $${paramIndex}
47
+ `;
48
+ const result = await client.query(query, [...updateValues, id]);
49
+ if (result.rowCount === 0) {
50
+ throw new IdNotFoundError();
51
+ }
52
+ const joinClauses = buildJoinClauses(operations);
53
+ const selectQuery = `
54
+ SELECT * FROM "${pluralResourceName}" ${joinClauses}
55
+ WHERE "_id" = $1 LIMIT 1
56
+ `;
57
+ const selectResult = await client.query(selectQuery, [id]);
58
+ if (selectResult.rows.length === 0) {
59
+ throw new IdNotFoundError();
60
+ }
61
+ return selectResult.rows[0];
62
+ }
63
+ catch (err) {
64
+ if (err instanceof IdNotFoundError) {
65
+ throw err;
66
+ }
67
+ if (err.code === '23505') {
68
+ throw new BadRequestError(`${pluralResourceName} has duplicate key violations`);
69
+ }
70
+ throw new BadRequestError(`Error updating ${pluralResourceName}: ${err.message}`);
71
+ }
72
+ }
@@ -0,0 +1,4 @@
1
+ import { Client } from 'pg';
2
+ import { Operation } from "../../operations/operation.js";
3
+ import { IEntity } from '@loomcore/common/models';
4
+ export declare function partialUpdateById<T extends IEntity>(client: Client, operations: Operation[], id: string, entity: Partial<T>, pluralResourceName: string): Promise<T>;
@@ -0,0 +1,42 @@
1
+ import { BadRequestError, IdNotFoundError } from "../../../errors/index.js";
2
+ import { buildJoinClauses } from '../utils/build-join-clauses.js';
3
+ import { columnsAndValuesFromEntity } from '../utils/columns-and-values-from-entity.js';
4
+ export async function partialUpdateById(client, operations, id, entity, pluralResourceName) {
5
+ try {
6
+ const { columns, values } = columnsAndValuesFromEntity(entity);
7
+ const updateColumns = columns.filter(col => col !== '"_id"');
8
+ const updateValues = values.filter((_, index) => columns[index] !== '"_id"');
9
+ if (updateColumns.length === 0) {
10
+ throw new BadRequestError('Cannot perform partial update with no fields to update');
11
+ }
12
+ const setClause = updateColumns.map((col, index) => `${col} = $${index + 1}`).join(', ');
13
+ const query = `
14
+ UPDATE "${pluralResourceName}"
15
+ SET ${setClause}
16
+ WHERE "_id" = $${updateValues.length + 1}
17
+ `;
18
+ const result = await client.query(query, [...updateValues, id]);
19
+ if (result.rowCount === 0) {
20
+ throw new IdNotFoundError();
21
+ }
22
+ const joinClauses = buildJoinClauses(operations);
23
+ const selectQuery = `
24
+ SELECT * FROM "${pluralResourceName}" ${joinClauses}
25
+ WHERE "_id" = $1 LIMIT 1
26
+ `;
27
+ const selectResult = await client.query(selectQuery, [id]);
28
+ if (selectResult.rows.length === 0) {
29
+ throw new IdNotFoundError();
30
+ }
31
+ return selectResult.rows[0];
32
+ }
33
+ catch (err) {
34
+ if (err instanceof IdNotFoundError) {
35
+ throw err;
36
+ }
37
+ if (err.code === '23505') {
38
+ throw new BadRequestError(`${pluralResourceName} has duplicate key violations`);
39
+ }
40
+ throw new BadRequestError(`Error updating ${pluralResourceName}: ${err.message}`);
41
+ }
42
+ }
@@ -0,0 +1,5 @@
1
+ import { Client } from 'pg';
2
+ import { IQueryOptions } from "@loomcore/common/models";
3
+ import { Operation } from "../../operations/operation.js";
4
+ import { IEntity } from '@loomcore/common/models';
5
+ export declare function update<T extends IEntity>(client: Client, queryObject: IQueryOptions, entity: Partial<T>, operations: Operation[], pluralResourceName: string): Promise<T[]>;
@@ -0,0 +1,48 @@
1
+ import { BadRequestError, NotFoundError } from "../../../errors/index.js";
2
+ import { buildWhereClause } from '../utils/build-where-clause.js';
3
+ import { buildJoinClauses } from '../utils/build-join-clauses.js';
4
+ import { buildOrderByClause } from '../utils/build-order-by-clause.js';
5
+ import { columnsAndValuesFromEntity } from '../utils/columns-and-values-from-entity.js';
6
+ export async function update(client, queryObject, entity, operations, pluralResourceName) {
7
+ try {
8
+ const { whereClause, values: whereValues } = buildWhereClause(queryObject);
9
+ const { columns, values: entityValues } = columnsAndValuesFromEntity(entity);
10
+ const updateColumns = columns.filter(col => col !== '"_id"');
11
+ const updateValues = entityValues.filter((_, index) => columns[index] !== '"_id"');
12
+ if (updateColumns.length === 0) {
13
+ throw new BadRequestError('Cannot perform update with no fields to update');
14
+ }
15
+ const setClause = updateColumns.map((col, index) => `${col} = $${index + 1}`).join(', ');
16
+ const whereClauseWithAdjustedParams = whereClause.replace(/\$(\d+)/g, (match, num) => {
17
+ const originalIndex = parseInt(num, 10);
18
+ return `$${originalIndex + updateValues.length}`;
19
+ });
20
+ const updateQuery = `
21
+ UPDATE "${pluralResourceName}"
22
+ SET ${setClause}
23
+ ${whereClauseWithAdjustedParams}
24
+ `;
25
+ const allUpdateValues = [...updateValues, ...whereValues];
26
+ const result = await client.query(updateQuery, allUpdateValues);
27
+ if (result.rowCount === 0) {
28
+ throw new NotFoundError('No records found matching update query');
29
+ }
30
+ const joinClauses = buildJoinClauses(operations);
31
+ const orderByClause = buildOrderByClause(queryObject);
32
+ const selectQuery = `
33
+ SELECT * FROM "${pluralResourceName}" ${joinClauses}
34
+ ${whereClause} ${orderByClause}
35
+ `.trim();
36
+ const selectResult = await client.query(selectQuery, whereValues);
37
+ return selectResult.rows;
38
+ }
39
+ catch (err) {
40
+ if (err instanceof NotFoundError) {
41
+ throw err;
42
+ }
43
+ if (err.code === '23505') {
44
+ throw new BadRequestError(`${pluralResourceName} has duplicate key violations`);
45
+ }
46
+ throw new BadRequestError(`Error updating ${pluralResourceName}: ${err.message}`);
47
+ }
48
+ }
@@ -0,0 +1,11 @@
1
+ import { Client } from "pg";
2
+ import { IMigration } from "./migration.interface.js";
3
+ export declare class CreateMigrationTableMigration implements IMigration {
4
+ private readonly client;
5
+ private readonly orgId?;
6
+ constructor(client: Client, orgId?: string | undefined);
7
+ index: number;
8
+ _id: string;
9
+ execute(): Promise<boolean>;
10
+ revert(): Promise<boolean>;
11
+ }
@@ -0,0 +1,52 @@
1
+ import { randomUUID } from 'crypto';
2
+ export class CreateMigrationTableMigration {
3
+ client;
4
+ orgId;
5
+ constructor(client, orgId) {
6
+ this.client = client;
7
+ this.orgId = orgId;
8
+ }
9
+ index = 1;
10
+ _id = randomUUID().toString();
11
+ async execute() {
12
+ let alreadyRun = false;
13
+ try {
14
+ await this.client.query(`
15
+ CREATE TABLE "migrations" (
16
+ "_id" VARCHAR(255) PRIMARY KEY,
17
+ "_orgId" VARCHAR(255),
18
+ "index" INTEGER NOT NULL,
19
+ "hasRun" BOOLEAN NOT NULL,
20
+ "reverted" BOOLEAN NOT NULL
21
+ )
22
+ `);
23
+ }
24
+ catch (error) {
25
+ if (error.data.error.includes('already exists')) {
26
+ alreadyRun = true;
27
+ }
28
+ else {
29
+ throw error;
30
+ }
31
+ }
32
+ if (!alreadyRun) {
33
+ if (this.orgId) {
34
+ await this.client.query(`
35
+ INSERT INTO "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") VALUES ('${this._id}', '${this.orgId}', ${this.index}, TRUE, FALSE);
36
+ `);
37
+ }
38
+ else {
39
+ await this.client.query(`
40
+ INSERT INTO "migrations" ("_id", "index", "hasRun", "reverted") VALUES ('${this._id}', ${this.index}, TRUE, FALSE);
41
+ `);
42
+ }
43
+ }
44
+ return true;
45
+ }
46
+ async revert() {
47
+ await this.client.query(`
48
+ DROP TABLE "migrations";
49
+ `);
50
+ return true;
51
+ }
52
+ }
@@ -0,0 +1,11 @@
1
+ import { Client } from "pg";
2
+ import { IMigration } from "./migration.interface.js";
3
+ export declare class CreateOrganizationTableMigration implements IMigration {
4
+ private readonly client;
5
+ private readonly orgId;
6
+ constructor(client: Client, orgId: string);
7
+ index: number;
8
+ _id: string;
9
+ execute(): Promise<boolean>;
10
+ revert(): Promise<boolean>;
11
+ }
@@ -0,0 +1,55 @@
1
+ import { randomUUID } from "crypto";
2
+ export class CreateOrganizationTableMigration {
3
+ client;
4
+ orgId;
5
+ constructor(client, orgId) {
6
+ this.client = client;
7
+ this.orgId = orgId;
8
+ }
9
+ index = 2;
10
+ _id = randomUUID().toString();
11
+ async execute() {
12
+ try {
13
+ await this.client.query(`
14
+ CREATE TABLE "organizations" (
15
+ "_id" VARCHAR(255) PRIMARY KEY,
16
+ "name" VARCHAR(255) NOT NULL,
17
+ "code" VARCHAR(255) NOT NULL,
18
+ "description" TEXT,
19
+ "status" INTEGER NOT NULL,
20
+ "isMetaOrg" BOOLEAN NOT NULL,
21
+ "authToken" TEXT,
22
+ "_created" TIMESTAMP NOT NULL,
23
+ "_createdBy" VARCHAR(255) NOT NULL,
24
+ "_updated" TIMESTAMP NOT NULL,
25
+ "_updatedBy" VARCHAR(255) NOT NULL,
26
+ "_deleted" TIMESTAMP,
27
+ "_deletedBy" VARCHAR(255)
28
+ )
29
+ `);
30
+ await this.client.query(`
31
+ Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${this._id}', '${this.orgId}', ${this.index}, TRUE, FALSE);
32
+ `);
33
+ return true;
34
+ }
35
+ catch (error) {
36
+ console.error('Error creating organization table:', error);
37
+ return false;
38
+ }
39
+ }
40
+ async revert() {
41
+ try {
42
+ await this.client.query(`
43
+ DROP TABLE "organizations";
44
+ `);
45
+ await this.client.query(`
46
+ Update "migrations" SET "reverted" = TRUE WHERE "_id" = '${this._id}';
47
+ `);
48
+ }
49
+ catch (error) {
50
+ console.error('Error reverting organization table:', error);
51
+ return false;
52
+ }
53
+ return true;
54
+ }
55
+ }
@@ -0,0 +1,11 @@
1
+ import { Client } from "pg";
2
+ import { IMigration } from "./migration.interface.js";
3
+ export declare class CreateUsersTableMigration implements IMigration {
4
+ private readonly client;
5
+ private readonly orgId?;
6
+ constructor(client: Client, orgId?: string | undefined);
7
+ index: number;
8
+ _id: string;
9
+ execute(): Promise<boolean>;
10
+ revert(): Promise<boolean>;
11
+ }
@@ -0,0 +1,65 @@
1
+ import { randomUUID } from "crypto";
2
+ export class CreateUsersTableMigration {
3
+ client;
4
+ orgId;
5
+ constructor(client, orgId) {
6
+ this.client = client;
7
+ this.orgId = orgId;
8
+ }
9
+ index = 3;
10
+ _id = randomUUID().toString();
11
+ async execute() {
12
+ try {
13
+ await this.client.query(`
14
+ CREATE TABLE "users" (
15
+ "_id" VARCHAR(255) PRIMARY KEY,
16
+ "_orgId" VARCHAR(255),
17
+ "email" VARCHAR(255) NOT NULL,
18
+ "firstName" VARCHAR(255),
19
+ "lastName" VARCHAR(255),
20
+ "displayName" VARCHAR(255),
21
+ "password" VARCHAR(255) NOT NULL,
22
+ "roles" TEXT[],
23
+ "_lastLoggedIn" TIMESTAMP,
24
+ "_lastPasswordChange" TIMESTAMP,
25
+ "_created" TIMESTAMP NOT NULL,
26
+ "_createdBy" VARCHAR(255) NOT NULL,
27
+ "_updated" TIMESTAMP NOT NULL,
28
+ "_updatedBy" VARCHAR(255) NOT NULL,
29
+ "_deleted" TIMESTAMP,
30
+ "_deletedBy" VARCHAR(255)
31
+ )
32
+ `);
33
+ if (this.orgId) {
34
+ await this.client.query(`
35
+ Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${this._id}', '${this.orgId}', ${this.index}, TRUE, FALSE);
36
+ `);
37
+ }
38
+ else {
39
+ await this.client.query(`
40
+ Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${this._id}', ${this.index}, TRUE, FALSE);
41
+ `);
42
+ }
43
+ }
44
+ catch (error) {
45
+ console.error('Error creating users table:', error);
46
+ return false;
47
+ }
48
+ return true;
49
+ }
50
+ async revert() {
51
+ try {
52
+ await this.client.query(`
53
+ DROP TABLE "users";
54
+ `);
55
+ await this.client.query(`
56
+ Update "migrations" SET "reverted" = TRUE WHERE "_id" = '${this._id}';
57
+ `);
58
+ }
59
+ catch (error) {
60
+ console.error('Error reverting users table:', error);
61
+ return false;
62
+ }
63
+ return true;
64
+ }
65
+ }
@@ -0,0 +1,11 @@
1
+ import { Client } from "pg";
2
+ import { IMigration } from "./index.js";
3
+ export declare class CreateRefreshTokenTableMigration implements IMigration {
4
+ private readonly client;
5
+ private readonly orgId?;
6
+ constructor(client: Client, orgId?: string | undefined);
7
+ index: number;
8
+ _id: string;
9
+ execute(): Promise<boolean>;
10
+ revert(): Promise<boolean>;
11
+ }
@@ -0,0 +1,57 @@
1
+ import { randomUUID } from "crypto";
2
+ export class CreateRefreshTokenTableMigration {
3
+ client;
4
+ orgId;
5
+ constructor(client, orgId) {
6
+ this.client = client;
7
+ this.orgId = orgId;
8
+ }
9
+ index = 4;
10
+ _id = randomUUID().toString();
11
+ async execute() {
12
+ try {
13
+ await this.client.query(`
14
+ CREATE TABLE "refreshTokens" (
15
+ "_id" VARCHAR(255) PRIMARY KEY,
16
+ "_orgId" VARCHAR(255),
17
+ "token" VARCHAR(255) NOT NULL,
18
+ "deviceId" VARCHAR(255) NOT NULL,
19
+ "userId" VARCHAR(255) NOT NULL,
20
+ "expiresOn" BIGINT NOT NULL,
21
+ "created" TIMESTAMP NOT NULL,
22
+ "createdBy" VARCHAR(255) NOT NULL
23
+ )
24
+ `);
25
+ if (this.orgId) {
26
+ await this.client.query(`
27
+ Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${this._id}', '${this.orgId}', ${this.index}, TRUE, FALSE);
28
+ `);
29
+ }
30
+ else {
31
+ await this.client.query(`
32
+ Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${this._id}', ${this.index}, TRUE, FALSE);
33
+ `);
34
+ }
35
+ return true;
36
+ }
37
+ catch (error) {
38
+ console.error('Error creating refresh token table:', error);
39
+ return false;
40
+ }
41
+ }
42
+ async revert() {
43
+ try {
44
+ await this.client.query(`
45
+ DROP TABLE "refresh_tokens";
46
+ `);
47
+ await this.client.query(`
48
+ Update "migrations" SET "reverted" = TRUE WHERE "_id" = '${this._id}';
49
+ `);
50
+ return true;
51
+ }
52
+ catch (error) {
53
+ console.error('Error reverting refresh token table:', error);
54
+ return false;
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,3 @@
1
+ export * from './migration.interface.js';
2
+ export * from './setup-for-multitenant.migration.js';
3
+ export * from './setup-for-auth.migration.js';
@@ -0,0 +1,3 @@
1
+ export * from './migration.interface.js';
2
+ export * from './setup-for-multitenant.migration.js';
3
+ export * from './setup-for-auth.migration.js';
@@ -0,0 +1,6 @@
1
+ import { Client } from "pg";
2
+ export declare class Migration {
3
+ private readonly client;
4
+ constructor(client: Client);
5
+ execute(): Promise<void>;
6
+ }
@@ -0,0 +1,6 @@
1
+ import { IEntity } from "@loomcore/common/models";
2
+ export interface IMigration extends IEntity {
3
+ index: number;
4
+ execute(): Promise<boolean>;
5
+ revert(): Promise<boolean>;
6
+ }
@@ -0,0 +1,14 @@
1
+ export class Migration {
2
+ client;
3
+ constructor(client) {
4
+ this.client = client;
5
+ }
6
+ async execute() {
7
+ await this.client.query(`
8
+ CREATE TABLE refresh_tokens (
9
+ id SERIAL PRIMARY KEY,
10
+ token VARCHAR(255) NOT NULL
11
+ )
12
+ `);
13
+ }
14
+ }
@@ -0,0 +1,2 @@
1
+ import { Client } from "pg";
2
+ export declare function runMigrations(client: Client, orgId: string, version?: number | null): Promise<boolean>;
@@ -0,0 +1,20 @@
1
+ import { CreateMigrationTableMigration, CreateOrganizationTableMigration, CreateUsersTableMigration } from "./index.js";
2
+ import { CreateRefreshTokenTableMigration } from "./004-create-refresh-token-table.migration.js";
3
+ export async function runMigrations(client, orgId, version = null) {
4
+ const migrations = [
5
+ new CreateMigrationTableMigration(client, orgId),
6
+ new CreateOrganizationTableMigration(client, orgId),
7
+ new CreateUsersTableMigration(client, orgId),
8
+ new CreateRefreshTokenTableMigration(client, orgId),
9
+ ];
10
+ let success = true;
11
+ for (const migration of migrations) {
12
+ if (version === null || migration.index <= version) {
13
+ success = await migration.execute();
14
+ if (!success) {
15
+ return false;
16
+ }
17
+ }
18
+ }
19
+ return success;
20
+ }
@@ -0,0 +1,2 @@
1
+ import { Client } from "pg";
2
+ export declare function setupDatabaseForAuth(client: Client, orgId?: string): Promise<boolean>;
@@ -0,0 +1,18 @@
1
+ import { CreateRefreshTokenTableMigration } from "./004-create-refresh-token-table.migration.js";
2
+ import { CreateMigrationTableMigration } from "./001-create-migrations-table.migration.js";
3
+ import { CreateUsersTableMigration } from "./003-create-users-table.migration.js";
4
+ export async function setupDatabaseForAuth(client, orgId) {
5
+ const migrations = [
6
+ new CreateMigrationTableMigration(client, orgId),
7
+ new CreateUsersTableMigration(client, orgId),
8
+ new CreateRefreshTokenTableMigration(client, orgId),
9
+ ];
10
+ let success = true;
11
+ for (const migration of migrations) {
12
+ success = await migration.execute();
13
+ if (!success) {
14
+ return false;
15
+ }
16
+ }
17
+ return success;
18
+ }
@@ -0,0 +1,2 @@
1
+ import { Client } from "pg";
2
+ export declare function setupDatabaseForMultitenant(client: Client, orgId: string): Promise<boolean>;
@@ -0,0 +1,16 @@
1
+ import { CreateMigrationTableMigration } from "./001-create-migrations-table.migration.js";
2
+ import { CreateOrganizationTableMigration } from "./002-create-organizations-table.migration.js";
3
+ export async function setupDatabaseForMultitenant(client, orgId) {
4
+ const migrations = [
5
+ new CreateMigrationTableMigration(client, orgId),
6
+ new CreateOrganizationTableMigration(client, orgId),
7
+ ];
8
+ let success = true;
9
+ for (const migration of migrations) {
10
+ success = await migration.execute();
11
+ if (!success) {
12
+ return false;
13
+ }
14
+ }
15
+ return success;
16
+ }
@@ -0,0 +1,31 @@
1
+ import { IQueryOptions, IModelSpec, IPagedResult, IEntity } from "@loomcore/common/models";
2
+ import { TSchema } from "@sinclair/typebox";
3
+ import { DeleteResult, IDatabase } from "../models/index.js";
4
+ import { Operation } from "../operations/operation.js";
5
+ import { Client } from 'pg';
6
+ export declare class PostgresDatabase implements IDatabase {
7
+ private client;
8
+ constructor(client: Client);
9
+ preprocessEntity<T extends IEntity>(entity: Partial<T>, modelSpec: TSchema): Partial<T>;
10
+ postprocessEntity<T extends IEntity>(entity: T, modelSpec: TSchema): T;
11
+ getAll<T extends IEntity>(operations: Operation[], pluralResourceName: string): Promise<T[]>;
12
+ get<T extends IEntity>(operations: Operation[], queryOptions: IQueryOptions, modelSpec: IModelSpec, pluralResourceName: string): Promise<IPagedResult<T>>;
13
+ getById<T extends IEntity>(operations: Operation[], queryObject: IQueryOptions, id: string, pluralResourceName: string): Promise<T | null>;
14
+ getCount(pluralResourceName: string): Promise<number>;
15
+ create<T extends IEntity>(entity: Partial<T>, pluralResourceName: string): Promise<{
16
+ insertedId: string;
17
+ entity: T;
18
+ }>;
19
+ createMany<T extends IEntity>(entities: Partial<T>[], pluralResourceName: string): Promise<{
20
+ insertedIds: string[];
21
+ entities: T[];
22
+ }>;
23
+ batchUpdate<T extends IEntity>(entities: Partial<T>[], operations: Operation[], queryObject: IQueryOptions, pluralResourceName: string): Promise<T[]>;
24
+ fullUpdateById<T extends IEntity>(operations: Operation[], id: string, entity: Partial<T>, pluralResourceName: string): Promise<T>;
25
+ partialUpdateById<T extends IEntity>(operations: Operation[], id: string, entity: Partial<T>, pluralResourceName: string): Promise<T>;
26
+ update<T extends IEntity>(queryObject: IQueryOptions, entity: Partial<T>, operations: Operation[], pluralResourceName: string): Promise<T[]>;
27
+ deleteById(id: string, pluralResourceName: string): Promise<DeleteResult>;
28
+ deleteMany(queryObject: IQueryOptions, pluralResourceName: string): Promise<DeleteResult>;
29
+ find<T extends IEntity>(queryObject: IQueryOptions, pluralResourceName: string): Promise<T[]>;
30
+ findOne<T extends IEntity>(queryObject: IQueryOptions, pluralResourceName: string): Promise<T | null>;
31
+ }