@terreno/api 0.0.1

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 (119) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +170 -0
  3. package/biome.jsonc +22 -0
  4. package/bunfig.toml +4 -0
  5. package/dist/api.d.ts +227 -0
  6. package/dist/api.js +1024 -0
  7. package/dist/api.test.d.ts +1 -0
  8. package/dist/api.test.js +2143 -0
  9. package/dist/auth.d.ts +50 -0
  10. package/dist/auth.js +512 -0
  11. package/dist/auth.test.d.ts +1 -0
  12. package/dist/auth.test.js +778 -0
  13. package/dist/errors.d.ts +75 -0
  14. package/dist/errors.js +216 -0
  15. package/dist/example.d.ts +1 -0
  16. package/dist/example.js +118 -0
  17. package/dist/expressServer.d.ts +35 -0
  18. package/dist/expressServer.js +436 -0
  19. package/dist/index.d.ts +14 -0
  20. package/dist/index.js +30 -0
  21. package/dist/logger.d.ts +23 -0
  22. package/dist/logger.js +249 -0
  23. package/dist/middleware.d.ts +10 -0
  24. package/dist/middleware.js +52 -0
  25. package/dist/notifiers/googleChatNotifier.d.ts +5 -0
  26. package/dist/notifiers/googleChatNotifier.js +130 -0
  27. package/dist/notifiers/googleChatNotifier.test.d.ts +1 -0
  28. package/dist/notifiers/googleChatNotifier.test.js +260 -0
  29. package/dist/notifiers/index.d.ts +3 -0
  30. package/dist/notifiers/index.js +19 -0
  31. package/dist/notifiers/slackNotifier.d.ts +5 -0
  32. package/dist/notifiers/slackNotifier.js +130 -0
  33. package/dist/notifiers/slackNotifier.test.d.ts +1 -0
  34. package/dist/notifiers/slackNotifier.test.js +259 -0
  35. package/dist/notifiers/zoomNotifier.d.ts +34 -0
  36. package/dist/notifiers/zoomNotifier.js +181 -0
  37. package/dist/notifiers/zoomNotifier.test.d.ts +1 -0
  38. package/dist/notifiers/zoomNotifier.test.js +370 -0
  39. package/dist/openApi.d.ts +60 -0
  40. package/dist/openApi.js +441 -0
  41. package/dist/openApi.test.d.ts +1 -0
  42. package/dist/openApi.test.js +445 -0
  43. package/dist/openApiBuilder.d.ts +419 -0
  44. package/dist/openApiBuilder.js +424 -0
  45. package/dist/openApiBuilder.test.d.ts +1 -0
  46. package/dist/openApiBuilder.test.js +509 -0
  47. package/dist/openApiEtag.d.ts +7 -0
  48. package/dist/openApiEtag.js +38 -0
  49. package/dist/permissions.d.ts +26 -0
  50. package/dist/permissions.js +331 -0
  51. package/dist/permissions.test.d.ts +1 -0
  52. package/dist/permissions.test.js +413 -0
  53. package/dist/plugins.d.ts +67 -0
  54. package/dist/plugins.js +315 -0
  55. package/dist/plugins.test.d.ts +1 -0
  56. package/dist/plugins.test.js +639 -0
  57. package/dist/populate.d.ts +14 -0
  58. package/dist/populate.js +315 -0
  59. package/dist/populate.test.d.ts +1 -0
  60. package/dist/populate.test.js +133 -0
  61. package/dist/response.d.ts +0 -0
  62. package/dist/response.js +1 -0
  63. package/dist/tests/bunSetup.d.ts +1 -0
  64. package/dist/tests/bunSetup.js +297 -0
  65. package/dist/tests/index.d.ts +1 -0
  66. package/dist/tests/index.js +17 -0
  67. package/dist/tests.d.ts +99 -0
  68. package/dist/tests.js +273 -0
  69. package/dist/transformers.d.ts +25 -0
  70. package/dist/transformers.js +217 -0
  71. package/dist/transformers.test.d.ts +1 -0
  72. package/dist/transformers.test.js +370 -0
  73. package/dist/utils.d.ts +11 -0
  74. package/dist/utils.js +143 -0
  75. package/dist/utils.test.d.ts +1 -0
  76. package/dist/utils.test.js +14 -0
  77. package/index.ts +1 -0
  78. package/package.json +88 -0
  79. package/src/__snapshots__/openApi.test.ts.snap +4814 -0
  80. package/src/__snapshots__/openApiBuilder.test.ts.snap +1485 -0
  81. package/src/api.test.ts +1661 -0
  82. package/src/api.ts +1036 -0
  83. package/src/auth.test.ts +550 -0
  84. package/src/auth.ts +408 -0
  85. package/src/errors.ts +225 -0
  86. package/src/example.ts +99 -0
  87. package/src/express.d.ts +5 -0
  88. package/src/expressServer.ts +387 -0
  89. package/src/index.ts +14 -0
  90. package/src/logger.ts +190 -0
  91. package/src/middleware.ts +18 -0
  92. package/src/notifiers/googleChatNotifier.test.ts +114 -0
  93. package/src/notifiers/googleChatNotifier.ts +47 -0
  94. package/src/notifiers/index.ts +3 -0
  95. package/src/notifiers/slackNotifier.test.ts +113 -0
  96. package/src/notifiers/slackNotifier.ts +55 -0
  97. package/src/notifiers/zoomNotifier.test.ts +207 -0
  98. package/src/notifiers/zoomNotifier.ts +111 -0
  99. package/src/openApi.test.ts +331 -0
  100. package/src/openApi.ts +494 -0
  101. package/src/openApiBuilder.test.ts +442 -0
  102. package/src/openApiBuilder.ts +636 -0
  103. package/src/openApiEtag.ts +40 -0
  104. package/src/permissions.test.ts +219 -0
  105. package/src/permissions.ts +228 -0
  106. package/src/plugins.test.ts +390 -0
  107. package/src/plugins.ts +289 -0
  108. package/src/populate.test.ts +65 -0
  109. package/src/populate.ts +258 -0
  110. package/src/response.ts +0 -0
  111. package/src/tests/bunSetup.ts +234 -0
  112. package/src/tests/index.ts +1 -0
  113. package/src/tests.ts +218 -0
  114. package/src/transformers.test.ts +202 -0
  115. package/src/transformers.ts +170 -0
  116. package/src/utils.test.ts +14 -0
  117. package/src/utils.ts +47 -0
  118. package/tsconfig.json +60 -0
  119. package/types.d.ts +17 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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 2020 Josh Gachnang
190
+ Copyright 2022 Flourish Health Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,170 @@
1
+ # @terreno/api
2
+
3
+ This library attempts to make creating REST APIs much easier with Express and Mongoose.
4
+ Most REST APIs wind up being a lot of boilerplate, so this tries to cut that down without turning
5
+ into a full blown framework of its own. This library is inspired by the
6
+ [Django-REST-Framework](https://www.django-rest-framework.org).
7
+
8
+ ### Coming soon:
9
+
10
+ A frontend library to consume these APIs with Redux Toolkit Query.
11
+
12
+ ## Getting started
13
+
14
+ To install:
15
+
16
+ npm install @terreno/api
17
+
18
+ yarn install @terreno/api
19
+
20
+ bun install @terreno/api
21
+
22
+ ## DateOnly Type
23
+
24
+ If you're using the `DateOnly` schema type from @terreno/api, you must register it with Mongoose as early as possible in your application—**before mongoose is imported elsewhere**. This ensures the custom type is available when your schemas are defined.
25
+
26
+ Add this to the top of your entry point (e.g., `src/index.ts`):
27
+
28
+ ```typescript
29
+ import {Schema} from "mongoose";
30
+ import {DateOnly} from "@terreno/api";
31
+
32
+ // Register DateOnly type before any models are loaded
33
+ (Schema.Types as any).DateOnly = DateOnly;
34
+ ```
35
+
36
+ Then you can use it in your schemas:
37
+
38
+ ```typescript
39
+ const eventSchema = new Schema({
40
+ eventDate: {type: Schema.Types.DateOnly},
41
+ });
42
+ ```
43
+
44
+ ## Usage
45
+
46
+ Assuming we have a model:
47
+
48
+ const foodSchema = new Schema<Food>({
49
+ name: String,
50
+ hidden: {type: Boolean, default: false},
51
+ ownerId: {type: "ObjectId", ref: "User"},
52
+ });
53
+ export const FoodModel = model("Food", foodSchema);
54
+
55
+ We can expose this model as an API like this:
56
+
57
+ import express from "express";
58
+ import {modelRouter, Permissions} from "@terreno/api";
59
+
60
+ const app = express();
61
+ app.use(
62
+ "/foods",
63
+ modelRouter(UserModel, {
64
+ permissions: {
65
+ list: [Permissions.IsAny],
66
+ create: [Permissions.IsAuthenticated],
67
+ read: [Permissions.IsAny],
68
+ update: [Permissions.IsOwner],
69
+ delete: [Permissions.IsAdmin],
70
+ },
71
+ })
72
+ );
73
+
74
+ Now we can perform operations on the Food model in a standard REST way. We've also added some permissioning.
75
+
76
+ # Gets a list of foods. Anyone can do this without being authenticated.
77
+ GET /foods
78
+ {
79
+ data: [{_id: "62c86d787c7e2db0bf286acd", name: "Carrots", hidden: false, ownerId: "62c44d9f003d9f8ee8cc9256"}],
80
+ more: false,
81
+ page: 1,
82
+ limit: 100
83
+ }
84
+
85
+ # Get a specific food. Anyone can do this.
86
+ GET /foods/62c86d787c7e2db0bf286acd
87
+ {_id: "62c86d787c7e2db0bf286acd", name: "Carrots", hidden: false, ownerId: "62c44d9f003d9f8ee8cc9256"}
88
+
89
+ # Creates a new food. Only authenticated users are allowed to do this.
90
+ POST /foods {name: "Broccoli", ownerId: "62c44d9f003d9f8ee8cc9256"}
91
+ {_id: "62c86d787c7e2db0bf286000", name: "Broccoli", hidden: false, ownerId: "62c44d9f003d9f8ee8cc9256"}
92
+
93
+ # Updates an existing food. Only the owner of the food can do this, otherwise an error code is returned.
94
+ PATCH /foods/62c86d787c7e2db0bf286acd {name: "Peas And Carrots"}
95
+ {_id: "62c86d787c7e2db0bf286acd", name: "Peas And Carrots", hidden: false, ownerId: "62c44d9f003d9f8ee8cc9256"}
96
+
97
+ # Deletes an existing food. Only admins are allowed to do this (users with `user.admin` set to true).
98
+ DELETE /foods/62c86d787c7e2db0bf286acd
99
+
100
+ You can create your own permissions functions. Check permissions.ts for some examples of how to write them.
101
+
102
+ ## Sentry
103
+ To enable Sentry, create a "src/sentryInstrumment.ts" file in your project.
104
+
105
+ ```
106
+ // Include dotenv here at the start if you're including configuration from dot files.
107
+ import "dotenv/config";
108
+
109
+ import * as Sentry from "@sentry/node";
110
+ import {nodeProfilingIntegration} from "@sentry/profiling-node";
111
+
112
+ if (process.env.NODE_ENV === "production" && !process.env.SENTRY_DSN) {
113
+ throw new Error("SENTRY_DSN must be set");
114
+ }
115
+
116
+ Sentry.init({
117
+ dsn: process.env.SENTRY_DSN,
118
+ integrations: [
119
+ // Only profile integration needs to be added, the rest are defaults and are already added,
120
+ // including Express, mongoose, HTTP, etc.
121
+ nodeProfilingIntegration() as any,
122
+ ],
123
+ // Debug can be helpful for figuruing out why something isn't working.
124
+ // debug: true,
125
+ environment: process.env.SENTRY_ENVIRONMENT ?? "production",
126
+ // Skip some errors if needed.
127
+ ignoreErrors: [
128
+ /^.*ECONNRESET*$/,
129
+ /^.*socket hang up*$/,
130
+ ],
131
+ // Set to 1.0 when testing the integration. Lower these to something like 0.1 or 0.2 in production. You can also use tracesSampler as a function to filter out ones
132
+ // you don't care about.
133
+ tracesSampleRate: 1.0,
134
+ profileSessionSampleRate: 1.0
135
+ });
136
+ ```
137
+
138
+ Then at the top of your src/index.ts file, before express is imported anywhere:
139
+
140
+ ```
141
+ import "./sentryInstrument";
142
+ ```
143
+
144
+ ## Example
145
+
146
+ To test out how the API works, you can look at and run [example.ts] by running `bun run compile` then running `bun dist/example.js` in /@terreno/api; while running, you can use a mongoDB client such as Compass to view collections.
147
+
148
+ ## Dev
149
+
150
+ To continuously compile the package:
151
+
152
+ bun run dev
153
+
154
+ To run tests, linting, and fixing up lint issues:
155
+
156
+ bun run lint
157
+ bun run lint:fix
158
+ bun run test
159
+
160
+ To see how your changes will affect the docs:
161
+
162
+ bun run docs
163
+ cd docs/
164
+ bunx http-server
165
+
166
+ A lot of dev may require using bun link. You'll want to keep the `bun run dev` window running to continuously compile:
167
+
168
+ bun link
169
+ cd $your-api-repo
170
+ bun link @terreno/api
package/biome.jsonc ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "root": false,
3
+ "$schema": "https://biomejs.dev/schemas/2.3.10/schema.json",
4
+ "extends": ["../biome.jsonc"],
5
+ "files": {
6
+ "includes": [
7
+ "package.json",
8
+ "src/**/*.ts",
9
+ "src/**/*.tsx",
10
+ "!src/populate.ts",
11
+ "!!src/populate.ts",
12
+ "!!**/node_modules",
13
+ "!!node_modules",
14
+ "!!**/dist",
15
+ "!!dist",
16
+ "!!**/build",
17
+ "!!build",
18
+ "!!**/coverage",
19
+ "!!coverage"
20
+ ]
21
+ }
22
+ }
package/bunfig.toml ADDED
@@ -0,0 +1,4 @@
1
+ [test]
2
+ preload = ["./src/tests/bunSetup.ts"]
3
+ root = "./src"
4
+
package/dist/api.d.ts ADDED
@@ -0,0 +1,227 @@
1
+ import express, { type NextFunction, type Request, type Response } from "express";
2
+ import mongoose, { type Document, type Model } from "mongoose";
3
+ import { type User } from "./auth";
4
+ import { type RESTPermissions } from "./permissions";
5
+ import type { PopulatePath } from "./populate";
6
+ import { type TerrenoTransformer } from "./transformers";
7
+ export type JSONPrimitive = string | number | boolean | null;
8
+ export interface JSONArray extends Array<JSONValue> {
9
+ }
10
+ export type JSONObject = {
11
+ [member: string]: JSONValue;
12
+ };
13
+ export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
14
+ export declare function addPopulateToQuery(builtQuery: mongoose.Query<any[], any, Record<string, never>, any>, populatePaths?: PopulatePath[]): mongoose.Query<any[], any, Record<string, never>, any, "find", Record<string, never>>;
15
+ /**
16
+ * @param a - the first number
17
+ * @param b - the second number
18
+ * @returns The sum of `a` and `b`
19
+ */
20
+ export type RESTMethod = "list" | "create" | "read" | "update" | "delete";
21
+ /**
22
+ * This is the main configuration.
23
+ * @param T - the base document type. This should not include Mongoose models, just the types of the object.
24
+ */
25
+ export interface modelRouterOptions<T> {
26
+ /**
27
+ * A group of method-level (create/read/update/delete/list) permissions.
28
+ * Determine if the user can perform the operation at all, and for read/update/delete methods,
29
+ * whether the user can perform the operation on the object referenced.
30
+ * */
31
+ permissions: RESTPermissions<T>;
32
+ /**
33
+ * Allow anonymous users to access the resource.
34
+ * Defaults to false.
35
+ */
36
+ allowAnonymous?: boolean;
37
+ /**
38
+ * A list of fields on the model that can be queried using standard comparisons for booleans,
39
+ * strings, dates
40
+ * (as ISOStrings), and numbers.
41
+ * For example:
42
+ * ?foo=true // boolean query
43
+ * ?foo=bar // string query
44
+ * ?foo=1 // number query
45
+ * ?foo=2022-07-23T02:34:07.118Z // date query (should first be encoded for query params, not shown here)
46
+ * Note: `limit` and `page` are automatically supported and are reserved. */
47
+ queryFields?: string[];
48
+ /**
49
+ * queryFilter is a function to parse the query params and see if the query should be allowed.
50
+ * This can be used for permissioning to make sure less privileged users are not making
51
+ * privileged queries. If a query should not be allowed,
52
+ * return `null` from the function and an empty query result will be returned to the client
53
+ * without an error. You can also throw an APIError to be explicit about the issues.
54
+ * You can transform the given query params by returning different values.
55
+ * If the query is acceptable as-is, return `query` as-is.
56
+ */
57
+ queryFilter?: (user?: User, query?: Record<string, any>) => Record<string, any> | null | Promise<Record<string, any> | null>;
58
+ /**
59
+ * Transformers allow data to be transformed before actions are executed,
60
+ * and serialized before being returned to the user.
61
+ *
62
+ * Transformers can be used to throw out fields that the user should not be able to write to, such as the `admin` flag.
63
+ * Serializers can be used to hide data from the client or change how it is presented. Serializers run after the data
64
+ * has been changed or queried but before returning to the client.
65
+ * @deprecated Use preCreate/preUpdate/preDelete hooks instead of transformer.transform. Use serialize instead of
66
+ * transformer.serialize.
67
+ * */
68
+ transformer?: TerrenoTransformer<T>;
69
+ /** Default sort for list operations. Can be a single field, a space-seperated list of fields, or an object.
70
+ * ?sort=foo // single field: foo ascending
71
+ * ?sort=-foo // single field: foo descending
72
+ * ?sort=-foo bar // multi field: foo descending, bar ascending
73
+ * ?sort=\{foo: 'ascending', bar: 'descending'\} // object: foo ascending, bar descending
74
+ *
75
+ * Note: you should have an index field on these fields or Mongo may slow down considerably.
76
+ * */
77
+ sort?: string | {
78
+ [key: string]: "ascending" | "descending";
79
+ };
80
+ /**
81
+ * Default queries to provide to Mongo before any user queries or transforms happen when making
82
+ * list queries. Accepts any Mongoose-style queries, and runs for all user types.
83
+ * defaultQueryParams: \{hidden: false\} // By default, don't show objects with hidden=true
84
+ * These can be overridden by the user if not disallowed by queryFilter. */
85
+ defaultQueryParams?: {
86
+ [key: string]: any;
87
+ };
88
+ /**
89
+ * Manages Mongoose populations before returning from all methods (list, read, create, etc).
90
+ * For each population:
91
+ * path: Accepts Mongoose-style populate strings for path. e.g. "user" or "users.userId"
92
+ * (for an array of subschemas with userId)
93
+ * fields: An array of strings to filter on the populated objects, following Mongoose's select
94
+ * rules. If each field starts a preceding "-", will act as a block list and only remove those
95
+ * fields. If each field does not start with a "-", will act as an allow list and only
96
+ * return those fields. Mixing allow and blocking is not supported. e.g. "-created updated"
97
+ * is an error.
98
+ * openApiComponent: If you have a component already registered,
99
+ * use that instead of autogenerating the types for the populated fields.
100
+ *
101
+ */
102
+ populatePaths?: PopulatePath[];
103
+ /** Default limit applied to list queries if not specified by the user. Defaults to 100. */
104
+ defaultLimit?: number;
105
+ /**
106
+ * Maximum query limit the user can request. Defaults to 500, and is the lowest of the limit
107
+ * query, max limit,
108
+ * or 500. */
109
+ maxLimit?: number;
110
+ /** */
111
+ endpoints?: (router: any) => void;
112
+ /**
113
+ * Hook that runs after `transformer.transform` but before the object is created.
114
+ * Can update the body fields based on the request or the user.
115
+ * Return null to return a generic 403 error. Throw an APIError to return a 400 with specific
116
+ * error information.
117
+ */
118
+ preCreate?: (value: any, request: express.Request) => T | Promise<T> | null;
119
+ /**
120
+ * Hook that runs after `transformer.transform` but before changes are made for update operations.
121
+ * Can update the body fields based on the request or the user.
122
+ * Also applies to all array operations. Return null to return a generic 403 error.
123
+ * Throw an APIError to return a 400 with specific error information.
124
+ *
125
+ * @param value - The request body relative to the model update (type: Partial<T>). Note: this does not contain the entire document to be updated, only the fields being updated.
126
+ * @param request - The Express request object.
127
+ */
128
+ preUpdate?: (value: Partial<T>, request: express.Request) => T | Promise<T> | null;
129
+ /**
130
+ * Hook that runs after `transformer.transform` but before the object is deleted.
131
+ * Return null to return a generic 403 error.
132
+ * Throw an APIError to return a 400 with specific error information.
133
+ *
134
+ * @param value - The document to be deleted, before the soft update of deleted: true (type: T).
135
+ * @param request - The Express request object.
136
+ */
137
+ preDelete?: (value: T, request: express.Request) => T | Promise<T> | null;
138
+ /**
139
+ * Hook that runs after the object is created but before the responseHandler serializes and
140
+ * returned. This is a good spot to perform dependent changes to other models or performing async
141
+ * tasks/side effects, such as sending a push notification.
142
+ * Throw an APIError to return a 400 with an error message.
143
+ */
144
+ postCreate?: (value: T, request: express.Request) => void | Promise<void>;
145
+ /**
146
+ * Hook that runs after the object is updated but before the responseHandler serializes and
147
+ * returned. This is a good spot to perform dependent changes to other models or perform async
148
+ * tasks/side effects, such as sending a push notification.
149
+ * Throw an APIError to return a 400 with an error message.
150
+ *
151
+ * @param value - The document after it has been updated (type: T).
152
+ * @param cleanedBody - The request body relative to the model update (type: Partial<T>).
153
+ * @param request - The Express request object.
154
+ * @param prevValue - The entire document before it was updated (type: T).
155
+ */
156
+ postUpdate?: (value: T, cleanedBody: Partial<T>, request: express.Request, prevValue: T) => void | Promise<void>;
157
+ /**
158
+ * Hook that runs after the object is deleted. This is a good spot to perform dependent changes
159
+ * to other models or performing async tasks/side effects, such as cascading object deletions.
160
+ * Throw an APIError to return a 400 with an error message.
161
+ *
162
+ * @param request - The Express request object.
163
+ * @param value - The document that was deleted, after the soft update of deleted: true (type: T).
164
+ */
165
+ postDelete?: (request: express.Request, value: T) => void | Promise<void>;
166
+ /** Hook that runs after the object is fetched but before it is serialized.
167
+ * Returns a promise so that asynchronous actions can be included in the function.
168
+ * Throw an APIError to return a 400 with an error message.
169
+ * @deprecated: Use responseHandler instead.
170
+ */
171
+ postGet?: (value: T, request: express.Request) => undefined | Promise<T>;
172
+ /** Hook that runs after the list of objects is fetched but before they are serialized.
173
+ * Returns a promise so that asynchronous actions can be included in the function.
174
+ * Throw an APIError to return a 400 with an error message.
175
+ * @deprecated: Use responseHandler instead.
176
+ */
177
+ postList?: (value: (Document<any, any, any> & T)[], request: express.Request) => Promise<(Document<any, any, any> & T)[]>;
178
+ /**
179
+ * Serialize an object or list of objects before returning to the client.
180
+ * This is a good spot to remove sensitive information from the object, such as passwords or API
181
+ * keys. Throw an APIError to return a 400 with an error message.
182
+ */
183
+ responseHandler?: (value: (Document<any, any, any> & T) | (Document<any, any, any> & T)[], method: "list" | "create" | "read" | "update" | "delete", request: express.Request, options: modelRouterOptions<T>) => Promise<JSONValue>;
184
+ /**
185
+ * The discriminatorKey that you passed when creating the Mongoose models. Defaults to __t. See:
186
+ * https://mongoosejs.com/docs/discriminators.html If this key is provided,
187
+ * you must provide the same key as part of the top level of the body when making performing
188
+ * update or delete operations on this model.
189
+ * \{discriminatorKey: "__t"\}
190
+ *
191
+ * PATCH \{__t: "SuperUser", name: "Foo"\} // __t is required or there will be a 404 error.
192
+ */
193
+ discriminatorKey?: string;
194
+ /**
195
+ * The OpenAPI generator for this server. This is used to generate the OpenAPI documentation.
196
+ */
197
+ openApi?: any;
198
+ /**
199
+ * Overwrite parts of the configuration for the OpenAPI generator.
200
+ * This will be merged with the generated configuration.
201
+ */
202
+ openApiOverwrite?: {
203
+ get?: any;
204
+ list?: any;
205
+ create?: any;
206
+ update?: any;
207
+ delete?: any;
208
+ };
209
+ /**
210
+ * Overwrite parts of the model properties for the OpenAPI generator.
211
+ * This will be merged with the generated configuration.
212
+ * This is useful if you add custom properties to the model during serialize, for example,
213
+ * that you want to be documented and typed in the SDK.
214
+ */
215
+ openApiExtraModelProperties?: any;
216
+ }
217
+ export declare function getModel(baseModel: Model<any>, body?: any, options?: modelRouterOptions<any>): mongoose.Model<any, {}, {}, {}, any, any, any>;
218
+ /**
219
+ * Create a set of CRUD routes given a Mongoose model $baseModel and configuration options.
220
+ *
221
+ * @param baseModel A Mongoose Model
222
+ * @param options Options for configuring the REST API, such as permissions, transformers, and hooks.
223
+ */
224
+ export declare function modelRouter<T>(baseModel: Model<T>, options: modelRouterOptions<T>): express.Router;
225
+ export declare const asyncHandler: (fn: any) => (req: Request, res: Response, next: NextFunction) => Promise<any>;
226
+ export declare const gooseRestRouter: typeof modelRouter;
227
+ export type GooseRESTOptions<T> = modelRouterOptions<T>;