@loomcore/api 0.2.2 → 0.2.4

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.
package/LICENSE CHANGED
@@ -1,201 +1,201 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,78 +1,78 @@
1
- # @loomcore/api
2
-
3
- An opinionated Node.js API toolkit using TypeScript, Express, and MongoDB (PostgreSQL support coming soon).
4
-
5
- This library provides a foundational structure for creating robust APIs, with a strong emphasis on multi-tenancy, user management, and OAuth 2.0 Code Flow authentication out of the box.
6
-
7
- ## Features
8
-
9
- - **Generic API Controller**: A base `ApiController` that automatically scaffolds a full suite of RESTful endpoints for any data model. This includes support for CRUD operations, batch updates, pagination, and counting.
10
- - **Built-in Multi-tenancy**: Optional, configuration-driven multi-tenancy. When enabled, all database operations are automatically scoped to the current user's organization, ensuring strict data isolation.
11
- - **Authentication & Authorization**: Integrated JWT-based authentication middleware (`isAuthorized`) to easily secure endpoints and support for OAuth 2.0 Code Flow, including the use of refresh tokens.
12
- - **User & Organization Management**: Pre-built services and controllers for common user and organization management tasks.
13
- - **Password Management**: Includes services for handling password reset requests and workflows.
14
- - **Email Service Integration**: A ready-to-use service for sending transactional emails (e.g., for password resets or welcome messages).
15
- - **Configuration-Driven**: Easily enable or disable features like multi-tenancy through a single configuration file.
16
- - **TypeScript & ES Modules**: A modern codebase written entirely in TypeScript, using ES Modules.
17
- - **Extensible Services**: A generic service layer that can be extended to add custom business logic while leveraging common data access patterns.
18
- - **Custom Error Handling**: A set of predefined error classes for consistent and meaningful API error responses.
19
- - **Schema Validation with TypeBox**: Leverages TypeBox for efficient, type-safe runtime data validation that integrates seamlessly with TypeScript.
20
- - **JSON Translations with TypeBox**: All data translations, from json input, to object persistence in a database, back to json output, flow through and are completely handled by json-schema-based Typebox schemas.
21
-
22
- ## Core Concepts
23
-
24
- ### Schema Validation with TypeBox
25
- This library uses `@sinclair/typebox` to define data models and validate incoming request bodies. This approach offers several key advantages:
26
-
27
- - **Type Safety**: TypeBox schemas are standard TypeScript, which means your data models and validation logic are fully type-checked at compile time.
28
- - **Performance**: It is a highly-performant validation library.
29
- - **Single Source of Truth**: Define your data structure once as a TypeBox schema and reuse it to automatically infer TypeScript types. This eliminates the need to maintain separate validation schemas and type definitions.
30
- - **Automatic Filtering**: By defining a `publicSchema` for your controllers, the API will automatically filter out sensitive fields (like passwords) before sending data back to the client.
31
-
32
- The framework is built around a few core components:
33
-
34
- 1. **`ApiController`**: You extend this class to create a new controller for a specific data model (e.g., `UsersController`). It automatically maps all the standard REST routes.
35
- 2. **`GenericApiService`**: A base service that provides the business logic for data operations (get, create, update, delete).
36
- 3. **`MultiTenantApiService`**: An extension of `GenericApiService` that adds the multi-tenancy layer, automatically filtering and tagging data with an organization ID.
37
-
38
- By extending these base classes, you can quickly stand up a new, fully-featured API endpoint with minimal boilerplate code.
39
-
40
- ## Testing
41
-
42
- ### PostgreSQL Testing
43
-
44
- The test suite supports two modes for PostgreSQL testing:
45
-
46
- 1. **pg-mem (default)**: Fast, in-memory PostgreSQL simulation. Use for most tests.
47
- ```bash
48
- npm run test:postgres
49
- ```
50
-
51
- 2. **Real PostgreSQL Container**: Full PostgreSQL compatibility for tests that require advanced features (e.g., LATERAL joins). Requires Docker.
52
- ```bash
53
- # Start the test database container
54
- npm run test:db:start
55
-
56
- # Wait for it to be ready (optional, tests will retry)
57
- ./scripts/wait-for-postgres.sh
58
-
59
- # Run tests with real PostgreSQL
60
- npm run test:postgres:real
61
-
62
- # Stop the container when done
63
- npm run test:db:stop
64
- ```
65
-
66
- The container uses port `5444` to avoid conflicts with local PostgreSQL instances. Set `USE_REAL_POSTGRES=true` to use the container instead of pg-mem.
67
-
68
- ## Example Usage
69
-
70
- ### Host Application
71
- A simple example usage of this library can be found in this [sample host application](https://github.com/thardy/monorepo-starter/tree/main/apps/api).
72
-
73
- The following five files will give you a good overview of the functionality bundled into this library:
74
- 1. [Main app file](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/index.ts) - Contains robust graceful shutdown, bundled in `expressUtils.performGracefulShutdown()`. Current example hardwired to MongoDb, but database abstraction and PostgreSQL support is currently in progress.
75
- 2. [Sample model](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/features/products/product.model.ts) - uses Typebox for validation and all json transforms.
76
- 3. [Sample controller](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/features/products/products.controller.ts) - Simply override ApiController to get full CRUD endpoints - getAll, get (with typed Filter object from querystring), getById, getCount, create, batchUpdate, fullUpdateById, partialUpdateById, and deleteById.
77
- 4. [Sample service](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/features/products/product.service.ts) - All CRUD handled by simply overriding GenericApiService. Override MultiTenantApiService instead to get full multi-tenant enforcement on all writes and queries. There are a ton of hooks available for overrides, including the ability to add joins on every get.
1
+ # @loomcore/api
2
+
3
+ An opinionated Node.js API toolkit using TypeScript, Express, and MongoDB (PostgreSQL support coming soon).
4
+
5
+ This library provides a foundational structure for creating robust APIs, with a strong emphasis on multi-tenancy, user management, and OAuth 2.0 Code Flow authentication out of the box.
6
+
7
+ ## Features
8
+
9
+ - **Generic API Controller**: A base `ApiController` that automatically scaffolds a full suite of RESTful endpoints for any data model. This includes support for CRUD operations, batch updates, pagination, and counting.
10
+ - **Built-in Multi-tenancy**: Optional, configuration-driven multi-tenancy. When enabled, all database operations are automatically scoped to the current user's organization, ensuring strict data isolation.
11
+ - **Authentication & Authorization**: Integrated JWT-based authentication middleware (`isAuthorized`) to easily secure endpoints and support for OAuth 2.0 Code Flow, including the use of refresh tokens.
12
+ - **User & Organization Management**: Pre-built services and controllers for common user and organization management tasks.
13
+ - **Password Management**: Includes services for handling password reset requests and workflows.
14
+ - **Email Service Integration**: A ready-to-use service for sending transactional emails (e.g., for password resets or welcome messages).
15
+ - **Configuration-Driven**: Easily enable or disable features like multi-tenancy through a single configuration file.
16
+ - **TypeScript & ES Modules**: A modern codebase written entirely in TypeScript, using ES Modules.
17
+ - **Extensible Services**: A generic service layer that can be extended to add custom business logic while leveraging common data access patterns.
18
+ - **Custom Error Handling**: A set of predefined error classes for consistent and meaningful API error responses.
19
+ - **Schema Validation with TypeBox**: Leverages TypeBox for efficient, type-safe runtime data validation that integrates seamlessly with TypeScript.
20
+ - **JSON Translations with TypeBox**: All data translations, from json input, to object persistence in a database, back to json output, flow through and are completely handled by json-schema-based Typebox schemas.
21
+
22
+ ## Core Concepts
23
+
24
+ ### Schema Validation with TypeBox
25
+ This library uses `@sinclair/typebox` to define data models and validate incoming request bodies. This approach offers several key advantages:
26
+
27
+ - **Type Safety**: TypeBox schemas are standard TypeScript, which means your data models and validation logic are fully type-checked at compile time.
28
+ - **Performance**: It is a highly-performant validation library.
29
+ - **Single Source of Truth**: Define your data structure once as a TypeBox schema and reuse it to automatically infer TypeScript types. This eliminates the need to maintain separate validation schemas and type definitions.
30
+ - **Automatic Filtering**: By defining a `publicSchema` for your controllers, the API will automatically filter out sensitive fields (like passwords) before sending data back to the client.
31
+
32
+ The framework is built around a few core components:
33
+
34
+ 1. **`ApiController`**: You extend this class to create a new controller for a specific data model (e.g., `UsersController`). It automatically maps all the standard REST routes.
35
+ 2. **`GenericApiService`**: A base service that provides the business logic for data operations (get, create, update, delete).
36
+ 3. **`MultiTenantApiService`**: An extension of `GenericApiService` that adds the multi-tenancy layer, automatically filtering and tagging data with an organization ID.
37
+
38
+ By extending these base classes, you can quickly stand up a new, fully-featured API endpoint with minimal boilerplate code.
39
+
40
+ ## Testing
41
+
42
+ ### PostgreSQL Testing
43
+
44
+ The test suite supports two modes for PostgreSQL testing:
45
+
46
+ 1. **pg-mem (default)**: Fast, in-memory PostgreSQL simulation. Use for most tests.
47
+ ```bash
48
+ npm run test:postgres
49
+ ```
50
+
51
+ 2. **Real PostgreSQL Container**: Full PostgreSQL compatibility for tests that require advanced features (e.g., LATERAL joins). Requires Docker.
52
+ ```bash
53
+ # Start the test database container
54
+ npm run test:db:start
55
+
56
+ # Wait for it to be ready (optional, tests will retry)
57
+ ./scripts/wait-for-postgres.sh
58
+
59
+ # Run tests with real PostgreSQL
60
+ npm run test:postgres:real
61
+
62
+ # Stop the container when done
63
+ npm run test:db:stop
64
+ ```
65
+
66
+ The container uses port `5444` to avoid conflicts with local PostgreSQL instances. Set `USE_REAL_POSTGRES=true` to use the container instead of pg-mem.
67
+
68
+ ## Example Usage
69
+
70
+ ### Host Application
71
+ A simple example usage of this library can be found in this [sample host application](https://github.com/thardy/monorepo-starter/tree/main/apps/api).
72
+
73
+ The following five files will give you a good overview of the functionality bundled into this library:
74
+ 1. [Main app file](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/index.ts) - Contains robust graceful shutdown, bundled in `expressUtils.performGracefulShutdown()`. Current example hardwired to MongoDb, but database abstraction and PostgreSQL support is currently in progress.
75
+ 2. [Sample model](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/features/products/product.model.ts) - uses Typebox for validation and all json transforms.
76
+ 3. [Sample controller](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/features/products/products.controller.ts) - Simply override ApiController to get full CRUD endpoints - getAll, get (with typed Filter object from querystring), getById, getCount, create, batchUpdate, fullUpdateById, partialUpdateById, and deleteById.
77
+ 4. [Sample service](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/features/products/product.service.ts) - All CRUD handled by simply overriding GenericApiService. Override MultiTenantApiService instead to get full multi-tenant enforcement on all writes and queries. There are a ton of hooks available for overrides, including the ability to add joins on every get.
78
78
  5. [Routes](https://github.com/thardy/monorepo-starter/blob/main/apps/api/src/server/routes/routes.ts) - full auth, organizations, and users endpoints/services are all bundled into the library
@@ -1,5 +1,5 @@
1
- import { Pool } from 'pg';
2
- import { IInitialDbMigrationConfig } from '../../../models/initial-database-config.interface.js';
1
+ import type { Pool } from "pg";
2
+ import type { IInitialDbMigrationConfig } from "../../../models/initial-database-config.interface.js";
3
3
  export interface SyntheticMigration {
4
4
  name: string;
5
5
  up: (context: {
@@ -1,33 +1,33 @@
1
- import { initializeSystemUserContext, EmptyUserContext, getSystemUserContext, isSystemUserContextInitialized } from '@loomcore/common/models';
2
- import { PostgresDatabase } from '../postgres.database.js';
3
- import { OrganizationService } from '../../../services/index.js';
4
- import { passwordUtils } from '../../../utils/index.js';
1
+ import { EmptyUserContext, getSystemUserContext, initializeSystemUserContext, isSystemUserContextInitialized, } from "@loomcore/common/models";
2
+ import { OrganizationService } from "../../../services/index.js";
3
+ import { passwordUtils } from "../../../utils/index.js";
4
+ import { PostgresDatabase } from "../postgres.database.js";
5
5
  export const getPostgresInitialSchema = (dbConfig) => {
6
6
  const migrations = [];
7
7
  const isMultiTenant = dbConfig.app.isMultiTenant;
8
8
  if (isMultiTenant && !dbConfig.multiTenant) {
9
- throw new Error('Multi-tenant configuration is enabled but multi-tenant configuration is not provided');
9
+ throw new Error("Multi-tenant configuration is enabled but multi-tenant configuration is not provided");
10
10
  }
11
11
  const isAuthEnabled = dbConfig.app.isAuthEnabled;
12
12
  const dbName = dbConfig.database.name.replace(/"/g, '""');
13
13
  migrations.push({
14
- name: '00000000000001_system-configurations',
14
+ name: "00000000000001_system-configurations",
15
15
  up: async ({ context: pool }) => {
16
- if (dbConfig.env === 'test') {
16
+ if (dbConfig.env === "test") {
17
17
  return;
18
18
  }
19
19
  await pool.query(`ALTER DATABASE "${dbName}" SET statement_timeout = '60s'`);
20
20
  },
21
21
  down: async ({ context: pool }) => {
22
- if (dbConfig.env === 'test') {
22
+ if (dbConfig.env === "test") {
23
23
  return;
24
24
  }
25
25
  await pool.query(`ALTER DATABASE "${dbName}" RESET statement_timeout`);
26
- }
26
+ },
27
27
  });
28
28
  if (isMultiTenant) {
29
29
  migrations.push({
30
- name: '00000000000002_schema-organizations',
30
+ name: "00000000000002_schema-organizations",
31
31
  up: async ({ context: pool }) => {
32
32
  await pool.query(`
33
33
  CREATE TABLE IF NOT EXISTS "organizations" (
@@ -49,14 +49,14 @@ export const getPostgresInitialSchema = (dbConfig) => {
49
49
  },
50
50
  down: async ({ context: pool }) => {
51
51
  await pool.query('DROP TABLE IF EXISTS "organizations"');
52
- }
52
+ },
53
53
  });
54
54
  }
55
55
  if (isAuthEnabled)
56
56
  migrations.push({
57
- name: '00000000000003_schema-persons',
57
+ name: "00000000000003_schema-persons",
58
58
  up: async ({ context: pool }) => {
59
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
59
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
60
60
  const personsUniqueConstraints = isMultiTenant
61
61
  ? `CONSTRAINT "uk_persons_org_external_id" UNIQUE ("_orgId", "external_id"),
62
62
  CONSTRAINT "uk_persons_org_ssn" UNIQUE ("_orgId", "ssn")`
@@ -91,13 +91,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
91
91
  await pool.query(`DROP INDEX IF EXISTS "idx_persons_external_id"`);
92
92
  await pool.query(`DROP INDEX IF EXISTS "idx_persons_ssn"`);
93
93
  await pool.query(`DROP TABLE IF EXISTS "persons"`);
94
- }
94
+ },
95
95
  });
96
96
  if (isAuthEnabled)
97
97
  migrations.push({
98
- name: '00000000000004_schema-users',
98
+ name: "00000000000004_schema-users",
99
99
  up: async ({ context: pool }) => {
100
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
100
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
101
101
  let uniqueConstraint = isMultiTenant
102
102
  ? 'CONSTRAINT "uk_users_email" UNIQUE ("_orgId", "email")'
103
103
  : 'CONSTRAINT "uk_users_email" UNIQUE ("email")';
@@ -131,13 +131,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
131
131
  await pool.query(`DROP INDEX IF EXISTS "idx_users_email"`);
132
132
  await pool.query(`DROP INDEX IF EXISTS "idx_users_person_id"`);
133
133
  await pool.query(`DROP TABLE IF EXISTS "users"`);
134
- }
134
+ },
135
135
  });
136
136
  if (isAuthEnabled)
137
137
  migrations.push({
138
- name: '00000000000005_schema-refresh-tokens',
138
+ name: "00000000000005_schema-refresh-tokens",
139
139
  up: async ({ context: pool }) => {
140
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
140
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
141
141
  await pool.query(`
142
142
  CREATE TABLE IF NOT EXISTS "refresh_tokens"(
143
143
  "_id" INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
@@ -154,13 +154,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
154
154
  },
155
155
  down: async ({ context: pool }) => {
156
156
  await pool.query('DROP TABLE IF EXISTS "refresh_tokens"');
157
- }
157
+ },
158
158
  });
159
159
  if (isAuthEnabled)
160
160
  migrations.push({
161
- name: '00000000000006_schema-password-reset-tokens',
161
+ name: "00000000000006_schema-password-reset-tokens",
162
162
  up: async ({ context: pool }) => {
163
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
163
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
164
164
  const uniqueConstraint = isMultiTenant
165
165
  ? 'CONSTRAINT "uk_passwordResetTokens_email" UNIQUE ("_orgId", "email")'
166
166
  : 'CONSTRAINT "uk_passwordResetTokens_email" UNIQUE ("email")';
@@ -183,13 +183,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
183
183
  },
184
184
  down: async ({ context: pool }) => {
185
185
  await pool.query('DROP TABLE IF EXISTS "password_reset_tokens"');
186
- }
186
+ },
187
187
  });
188
188
  if (isAuthEnabled)
189
189
  migrations.push({
190
- name: '00000000000007_schema-roles',
190
+ name: "00000000000007_schema-roles",
191
191
  up: async ({ context: pool }) => {
192
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
192
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
193
193
  const uniqueConstraint = isMultiTenant
194
194
  ? 'CONSTRAINT "uk_roles_name" UNIQUE ("_orgId", "name")'
195
195
  : 'CONSTRAINT "uk_roles_name" UNIQUE ("name")';
@@ -205,13 +205,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
205
205
  },
206
206
  down: async ({ context: pool }) => {
207
207
  await pool.query('DROP TABLE IF EXISTS "roles"');
208
- }
208
+ },
209
209
  });
210
210
  if (isAuthEnabled)
211
211
  migrations.push({
212
- name: '00000000000008_schema-user-roles',
212
+ name: "00000000000008_schema-user-roles",
213
213
  up: async ({ context: pool }) => {
214
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
214
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
215
215
  const uniqueConstraint = isMultiTenant
216
216
  ? 'CONSTRAINT "uk_user_roles" UNIQUE ("_orgId", "user_id", "role_id")'
217
217
  : 'CONSTRAINT "uk_user_roles" UNIQUE ("user_id", "role_id")';
@@ -235,13 +235,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
235
235
  },
236
236
  down: async ({ context: pool }) => {
237
237
  await pool.query('DROP TABLE IF EXISTS "user_roles"');
238
- }
238
+ },
239
239
  });
240
240
  if (isAuthEnabled)
241
241
  migrations.push({
242
- name: '00000000000009_schema-features',
242
+ name: "00000000000009_schema-features",
243
243
  up: async ({ context: pool }) => {
244
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
244
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
245
245
  const uniqueConstraint = isMultiTenant
246
246
  ? 'CONSTRAINT "uk_features" UNIQUE ("_orgId", "name")'
247
247
  : 'CONSTRAINT "uk_features" UNIQUE ("name")';
@@ -257,13 +257,13 @@ export const getPostgresInitialSchema = (dbConfig) => {
257
257
  },
258
258
  down: async ({ context: pool }) => {
259
259
  await pool.query('DROP TABLE IF EXISTS "features"');
260
- }
260
+ },
261
261
  });
262
262
  if (isAuthEnabled)
263
263
  migrations.push({
264
- name: '00000000000010_schema-authorizations',
264
+ name: "00000000000010_schema-authorizations",
265
265
  up: async ({ context: pool }) => {
266
- const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER,' : '';
266
+ const orgColumnDef = isMultiTenant ? '"_orgId" INTEGER NOT NULL,' : "";
267
267
  const uniqueConstraint = isMultiTenant
268
268
  ? 'CONSTRAINT "uk_authorizations" UNIQUE ("_orgId", "role_id", "feature_id")'
269
269
  : 'CONSTRAINT "uk_authorizations" UNIQUE ("role_id", "feature_id")';
@@ -290,41 +290,46 @@ export const getPostgresInitialSchema = (dbConfig) => {
290
290
  },
291
291
  down: async ({ context: pool }) => {
292
292
  await pool.query('DROP TABLE IF EXISTS "authorizations"');
293
- }
293
+ },
294
294
  });
295
295
  if (isMultiTenant) {
296
296
  migrations.push({
297
- name: '00000000000011_data-meta-org',
297
+ name: "00000000000011_data-meta-org",
298
298
  up: async ({ context: pool }) => {
299
299
  const result = await pool.query(`
300
300
  INSERT INTO "organizations"("name", "code", "status", "is_meta_org", "_created", "_createdBy")
301
301
  VALUES($1, $2, 1, true, NOW(), 0)
302
302
  RETURNING "_id", "name", "code", "status", "is_meta_org", "_created", "_createdBy"
303
- `, [dbConfig.multiTenant?.metaOrgName, dbConfig.multiTenant?.metaOrgCode]);
303
+ `, [
304
+ dbConfig.multiTenant?.metaOrgName,
305
+ dbConfig.multiTenant?.metaOrgCode,
306
+ ]);
304
307
  if (result.rowCount === 0) {
305
- throw new Error('Failed to create meta organization');
308
+ throw new Error("Failed to create meta organization");
306
309
  }
307
- initializeSystemUserContext(dbConfig.email?.systemEmailAddress || 'system@example.com', result.rows[0]);
310
+ initializeSystemUserContext(dbConfig.email?.systemEmailAddress || "system@example.com", result.rows[0]);
308
311
  },
309
312
  down: async ({ context: pool }) => {
310
313
  await pool.query(`DELETE FROM "organizations" WHERE "is_meta_org" = TRUE`);
311
- }
314
+ },
312
315
  });
313
316
  }
314
317
  if (isAuthEnabled && dbConfig.adminUser) {
315
318
  migrations.push({
316
- name: '00000000000012_data-admin-user',
319
+ name: "00000000000012_data-admin-user",
317
320
  up: async ({ context: pool }) => {
318
321
  if (!isSystemUserContextInitialized()) {
319
322
  const errorMessage = isMultiTenant
320
- ? 'SystemUserContext has not been initialized. The meta-org migration (00000000000011_data-meta-org) should have run before this migration. ' +
321
- 'Please ensure metaOrgName and metaOrgCode are provided in your dbConfig.'
322
- : 'BUG: SystemUserContext has not been initialized. For non-multi-tenant setups, SystemUserContext should be initialized before migrations run.';
323
- console.error('❌ Migration Error:', errorMessage);
323
+ ? "SystemUserContext has not been initialized. The meta-org migration (00000000000011_data-meta-org) should have run before this migration. " +
324
+ "Please ensure metaOrgName and metaOrgCode are provided in your dbConfig."
325
+ : "BUG: SystemUserContext has not been initialized. For non-multi-tenant setups, SystemUserContext should be initialized before migrations run.";
326
+ console.error("❌ Migration Error:", errorMessage);
324
327
  throw new Error(errorMessage);
325
328
  }
326
329
  const systemUserContext = getSystemUserContext();
327
- const orgId = isMultiTenant ? systemUserContext.organization?._id : undefined;
330
+ const orgId = isMultiTenant
331
+ ? systemUserContext.organization?._id
332
+ : undefined;
328
333
  const hashedPassword = await passwordUtils.hashPassword(dbConfig.adminUser.password);
329
334
  const email = dbConfig.adminUser.email.toLowerCase();
330
335
  const client = await pool.connect();
@@ -353,30 +358,34 @@ export const getPostgresInitialSchema = (dbConfig) => {
353
358
  down: async ({ context: pool }) => {
354
359
  if (!dbConfig.adminUser?.email)
355
360
  return;
356
- await pool.query(`DELETE FROM "users" WHERE "email" = $1`, [dbConfig.adminUser.email.toLowerCase()]);
357
- }
361
+ await pool.query(`DELETE FROM "users" WHERE "email" = $1`, [
362
+ dbConfig.adminUser.email.toLowerCase(),
363
+ ]);
364
+ },
358
365
  });
359
366
  }
360
367
  if (isAuthEnabled && dbConfig.adminUser) {
361
368
  migrations.push({
362
- name: '00000000000013_data-admin-authorizations',
369
+ name: "00000000000013_data-admin-authorizations",
363
370
  up: async ({ context: pool }) => {
364
371
  const client = await pool.connect();
365
372
  try {
366
373
  const database = new PostgresDatabase(client);
367
374
  const organizationService = new OrganizationService(database);
368
- const metaOrg = isMultiTenant ? await organizationService.getMetaOrg(EmptyUserContext) : undefined;
375
+ const metaOrg = isMultiTenant
376
+ ? await organizationService.getMetaOrg(EmptyUserContext)
377
+ : undefined;
369
378
  if (isMultiTenant && !metaOrg) {
370
- throw new Error('Meta organization not found. Ensure meta-org migration ran successfully.');
379
+ throw new Error("Meta organization not found. Ensure meta-org migration ran successfully.");
371
380
  }
372
381
  const email = dbConfig.adminUser.email.toLowerCase();
373
382
  const userResult = await client.query(`SELECT "_id" FROM "users" WHERE "email" = $1`, [email]);
374
383
  const adminUserRow = userResult.rows[0];
375
384
  if (!adminUserRow) {
376
- throw new Error('Admin user not found. Ensure admin-user migration ran successfully.');
385
+ throw new Error("Admin user not found. Ensure admin-user migration ran successfully.");
377
386
  }
378
387
  const adminUserId = adminUserRow._id;
379
- await client.query('BEGIN');
388
+ await client.query("BEGIN");
380
389
  try {
381
390
  const roleResult = isMultiTenant
382
391
  ? await client.query(`
@@ -390,7 +399,7 @@ export const getPostgresInitialSchema = (dbConfig) => {
390
399
  RETURNING "_id"
391
400
  `);
392
401
  if (roleResult.rowCount === 0) {
393
- throw new Error('Failed to create admin role');
402
+ throw new Error("Failed to create admin role");
394
403
  }
395
404
  const roleId = roleResult.rows[0]._id;
396
405
  const userRoleResult = isMultiTenant
@@ -403,7 +412,7 @@ export const getPostgresInitialSchema = (dbConfig) => {
403
412
  VALUES($1, $2, NOW(), 0)
404
413
  `, [adminUserId, roleId]);
405
414
  if (userRoleResult.rowCount === 0) {
406
- throw new Error('Failed to create user role');
415
+ throw new Error("Failed to create user role");
407
416
  }
408
417
  const featureResult = isMultiTenant
409
418
  ? await client.query(`
@@ -417,7 +426,7 @@ export const getPostgresInitialSchema = (dbConfig) => {
417
426
  RETURNING "_id"
418
427
  `);
419
428
  if (featureResult.rowCount === 0) {
420
- throw new Error('Failed to create admin feature');
429
+ throw new Error("Failed to create admin feature");
421
430
  }
422
431
  const featureId = featureResult.rows[0]._id;
423
432
  const authorizationResult = isMultiTenant
@@ -436,12 +445,12 @@ export const getPostgresInitialSchema = (dbConfig) => {
436
445
  VALUES($1, $2, NOW(), 0)
437
446
  `, [roleId, featureId]);
438
447
  if (authorizationResult.rowCount === 0) {
439
- throw new Error('Failed to create admin authorization');
448
+ throw new Error("Failed to create admin authorization");
440
449
  }
441
- await client.query('COMMIT');
450
+ await client.query("COMMIT");
442
451
  }
443
452
  catch (error) {
444
- await client.query('ROLLBACK');
453
+ await client.query("ROLLBACK");
445
454
  throw error;
446
455
  }
447
456
  }
@@ -454,10 +463,12 @@ export const getPostgresInitialSchema = (dbConfig) => {
454
463
  try {
455
464
  const database = new PostgresDatabase(client);
456
465
  const organizationService = new OrganizationService(database);
457
- const metaOrg = isMultiTenant ? await organizationService.getMetaOrg(EmptyUserContext) : undefined;
466
+ const metaOrg = isMultiTenant
467
+ ? await organizationService.getMetaOrg(EmptyUserContext)
468
+ : undefined;
458
469
  if (isMultiTenant && !metaOrg)
459
470
  return;
460
- await client.query('BEGIN');
471
+ await client.query("BEGIN");
461
472
  try {
462
473
  if (isMultiTenant) {
463
474
  await client.query(`
@@ -517,17 +528,17 @@ export const getPostgresInitialSchema = (dbConfig) => {
517
528
  WHERE "name" = 'admin'
518
529
  `);
519
530
  }
520
- await client.query('COMMIT');
531
+ await client.query("COMMIT");
521
532
  }
522
533
  catch (error) {
523
- await client.query('ROLLBACK');
534
+ await client.query("ROLLBACK");
524
535
  throw error;
525
536
  }
526
537
  }
527
538
  finally {
528
539
  client.release();
529
540
  }
530
- }
541
+ },
531
542
  });
532
543
  }
533
544
  return migrations;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loomcore/api",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "private": false,
5
5
  "description": "Loom Core Api - An opinionated Node.js api using Typescript, Express, and MongoDb or PostgreSQL",
6
6
  "scripts": {
@@ -55,7 +55,7 @@
55
55
  "dependencies": {
56
56
  "jsonwebtoken": "^9.0.2",
57
57
  "node-mailjet": "^6.0.8",
58
- "qs": "^6.15.0"
58
+ "qs": "^6.15.2"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@loomcore/common": "^0.0.70",