@terreno/api 0.0.18 → 0.2.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.
- package/README.md +73 -3
- package/dist/api.d.ts +96 -3
- package/dist/api.js +159 -11
- package/dist/api.test.js +906 -2
- package/dist/auth.js +3 -1
- package/dist/betterAuth.d.ts +91 -0
- package/dist/betterAuth.js +8 -0
- package/dist/betterAuth.test.d.ts +1 -0
- package/dist/betterAuth.test.js +181 -0
- package/dist/betterAuthApp.d.ts +22 -0
- package/dist/betterAuthApp.js +38 -0
- package/dist/betterAuthApp.test.d.ts +1 -0
- package/dist/betterAuthApp.test.js +242 -0
- package/dist/betterAuthSetup.d.ts +60 -0
- package/dist/betterAuthSetup.js +278 -0
- package/dist/betterAuthSetup.test.d.ts +1 -0
- package/dist/betterAuthSetup.test.js +684 -0
- package/dist/errors.js +14 -11
- package/dist/example.js +7 -7
- package/dist/expressServer.js +2 -2
- package/dist/githubAuth.test.js +3 -3
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/openApi.test.js +8 -5
- package/dist/openApiBuilder.d.ts +69 -1
- package/dist/openApiBuilder.js +109 -5
- package/dist/openApiValidator.d.ts +296 -0
- package/dist/openApiValidator.js +698 -0
- package/dist/openApiValidator.test.d.ts +1 -0
- package/dist/openApiValidator.test.js +346 -0
- package/dist/plugins.test.js +3 -3
- package/dist/terrenoApp.d.ts +189 -0
- package/dist/terrenoApp.js +352 -0
- package/dist/terrenoApp.test.d.ts +1 -0
- package/dist/terrenoApp.test.js +264 -0
- package/dist/terrenoPlugin.d.ts +38 -0
- package/dist/terrenoPlugin.js +2 -0
- package/dist/tests.js +34 -24
- package/package.json +8 -2
- package/src/__snapshots__/openApi.test.ts.snap +399 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +108 -0
- package/src/api.test.ts +743 -2
- package/src/api.ts +270 -6
- package/src/auth.ts +3 -1
- package/src/betterAuth.test.ts +160 -0
- package/src/betterAuth.ts +104 -0
- package/src/betterAuthApp.test.ts +114 -0
- package/src/betterAuthApp.ts +60 -0
- package/src/betterAuthSetup.test.ts +485 -0
- package/src/betterAuthSetup.ts +251 -0
- package/src/errors.ts +14 -11
- package/src/example.ts +7 -7
- package/src/expressServer.ts +4 -5
- package/src/githubAuth.test.ts +3 -3
- package/src/index.ts +6 -0
- package/src/openApi.test.ts +8 -5
- package/src/openApiBuilder.ts +188 -15
- package/src/openApiValidator.test.ts +241 -0
- package/src/openApiValidator.ts +860 -0
- package/src/plugins.test.ts +3 -3
- package/src/terrenoApp.test.ts +201 -0
- package/src/terrenoApp.ts +347 -0
- package/src/terrenoPlugin.ts +39 -0
- package/src/tests.ts +34 -24
- package/.cursorrules +0 -107
- package/.windsurfrules +0 -107
- package/AGENTS.md +0 -313
- package/dist/response.d.ts +0 -0
- package/dist/response.js +0 -1
- package/index.ts +0 -1
- package/src/response.ts +0 -0
package/src/plugins.test.ts
CHANGED
|
@@ -39,9 +39,9 @@ interface StuffModelType extends Model<Stuff> {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
const stuffSchema = new Schema<Stuff>({
|
|
42
|
-
date: DateOnly,
|
|
43
|
-
name: String,
|
|
44
|
-
ownerId: String,
|
|
42
|
+
date: {description: "The date associated with this item", type: DateOnly as any},
|
|
43
|
+
name: {description: "The name of the item", type: String},
|
|
44
|
+
ownerId: {description: "The user who owns this item", type: String},
|
|
45
45
|
});
|
|
46
46
|
|
|
47
47
|
stuffSchema.plugin(isDeletedPlugin);
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
import supertest from "supertest";
|
|
4
|
+
|
|
5
|
+
import {modelRouter} from "./api";
|
|
6
|
+
import {Permissions} from "./permissions";
|
|
7
|
+
import {TerrenoApp} from "./terrenoApp";
|
|
8
|
+
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
9
|
+
import {authAsUser, FoodModel, setupDb, UserModel} from "./tests";
|
|
10
|
+
|
|
11
|
+
describe("TerrenoApp", () => {
|
|
12
|
+
const originalEnv = process.env;
|
|
13
|
+
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
process.env = {
|
|
16
|
+
...originalEnv,
|
|
17
|
+
REFRESH_TOKEN_SECRET: "test-refresh-secret",
|
|
18
|
+
SESSION_SECRET: "test-session-secret",
|
|
19
|
+
TOKEN_EXPIRES_IN: "1h",
|
|
20
|
+
TOKEN_ISSUER: "test-issuer",
|
|
21
|
+
TOKEN_SECRET: "test-secret",
|
|
22
|
+
};
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
process.env = originalEnv;
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe("build", () => {
|
|
30
|
+
it("returns an express application without listening", () => {
|
|
31
|
+
const app = new TerrenoApp({
|
|
32
|
+
skipListen: true,
|
|
33
|
+
userModel: UserModel as any,
|
|
34
|
+
}).build();
|
|
35
|
+
|
|
36
|
+
expect(app).toBeDefined();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("creates server with custom corsOrigin", () => {
|
|
40
|
+
const app = new TerrenoApp({
|
|
41
|
+
corsOrigin: "https://example.com",
|
|
42
|
+
skipListen: true,
|
|
43
|
+
userModel: UserModel as any,
|
|
44
|
+
}).build();
|
|
45
|
+
|
|
46
|
+
expect(app).toBeDefined();
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe("start", () => {
|
|
51
|
+
it("returns an express application with skipListen", () => {
|
|
52
|
+
const app = new TerrenoApp({
|
|
53
|
+
skipListen: true,
|
|
54
|
+
userModel: UserModel as any,
|
|
55
|
+
}).start();
|
|
56
|
+
|
|
57
|
+
expect(app).toBeDefined();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("register with modelRouter", () => {
|
|
62
|
+
let admin: any;
|
|
63
|
+
|
|
64
|
+
beforeEach(async () => {
|
|
65
|
+
[admin] = await setupDb();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("mounts model router at the specified path", async () => {
|
|
69
|
+
const foodRegistration = modelRouter("/food", FoodModel, {
|
|
70
|
+
allowAnonymous: true,
|
|
71
|
+
permissions: {
|
|
72
|
+
create: [Permissions.IsAny],
|
|
73
|
+
delete: [Permissions.IsAny],
|
|
74
|
+
list: [Permissions.IsAny],
|
|
75
|
+
read: [Permissions.IsAny],
|
|
76
|
+
update: [Permissions.IsAny],
|
|
77
|
+
},
|
|
78
|
+
sort: "-created",
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
expect(foodRegistration.__type).toBe("modelRouter");
|
|
82
|
+
expect(foodRegistration.path).toBe("/food");
|
|
83
|
+
|
|
84
|
+
const app = new TerrenoApp({
|
|
85
|
+
skipListen: true,
|
|
86
|
+
userModel: UserModel as any,
|
|
87
|
+
})
|
|
88
|
+
.register(foodRegistration)
|
|
89
|
+
.build();
|
|
90
|
+
|
|
91
|
+
await FoodModel.create({
|
|
92
|
+
calories: 100,
|
|
93
|
+
name: "Apple",
|
|
94
|
+
ownerId: admin._id,
|
|
95
|
+
source: {name: "Nature"},
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const agent = await authAsUser(app, "admin");
|
|
99
|
+
const res = await agent.get("/food").expect(200);
|
|
100
|
+
expect(res.body.data).toHaveLength(1);
|
|
101
|
+
expect(res.body.data[0].name).toBe("Apple");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("supports chaining multiple registrations", async () => {
|
|
105
|
+
const foodRegistration = modelRouter("/food", FoodModel, {
|
|
106
|
+
allowAnonymous: true,
|
|
107
|
+
permissions: {
|
|
108
|
+
create: [Permissions.IsAny],
|
|
109
|
+
delete: [Permissions.IsAny],
|
|
110
|
+
list: [Permissions.IsAny],
|
|
111
|
+
read: [Permissions.IsAny],
|
|
112
|
+
update: [Permissions.IsAny],
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const app = new TerrenoApp({
|
|
117
|
+
skipListen: true,
|
|
118
|
+
userModel: UserModel as any,
|
|
119
|
+
})
|
|
120
|
+
.register(foodRegistration)
|
|
121
|
+
.build();
|
|
122
|
+
|
|
123
|
+
expect(app).toBeDefined();
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
describe("register with plugin", () => {
|
|
128
|
+
it("calls plugin.register with the express app", () => {
|
|
129
|
+
const registerFn = mock(() => {});
|
|
130
|
+
const plugin: TerrenoPlugin = {
|
|
131
|
+
register: registerFn,
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const app = new TerrenoApp({
|
|
135
|
+
skipListen: true,
|
|
136
|
+
userModel: UserModel as any,
|
|
137
|
+
})
|
|
138
|
+
.register(plugin)
|
|
139
|
+
.build();
|
|
140
|
+
|
|
141
|
+
expect(registerFn).toHaveBeenCalledTimes(1);
|
|
142
|
+
// Verify the plugin received the express app
|
|
143
|
+
const calledWith = (registerFn.mock.calls as any[][])[0][0];
|
|
144
|
+
expect(calledWith).toBe(app);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe("addMiddleware", () => {
|
|
149
|
+
it("runs request handler middleware", async () => {
|
|
150
|
+
let middlewareCalled = false;
|
|
151
|
+
const middleware: express.RequestHandler = (_req, _res, next) => {
|
|
152
|
+
middlewareCalled = true;
|
|
153
|
+
next();
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const app = new TerrenoApp({
|
|
157
|
+
skipListen: true,
|
|
158
|
+
userModel: UserModel as any,
|
|
159
|
+
})
|
|
160
|
+
.addMiddleware(middleware)
|
|
161
|
+
.build();
|
|
162
|
+
|
|
163
|
+
await supertest(app).get("/nonexistent").expect(404);
|
|
164
|
+
expect(middlewareCalled).toBe(true);
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
describe("modelRouter overload", () => {
|
|
169
|
+
it("returns ModelRouterRegistration when path is provided", () => {
|
|
170
|
+
const result = modelRouter("/food", FoodModel, {
|
|
171
|
+
permissions: {
|
|
172
|
+
create: [Permissions.IsAny],
|
|
173
|
+
delete: [Permissions.IsAny],
|
|
174
|
+
list: [Permissions.IsAny],
|
|
175
|
+
read: [Permissions.IsAny],
|
|
176
|
+
update: [Permissions.IsAny],
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
expect(result.__type).toBe("modelRouter");
|
|
181
|
+
expect(result.path).toBe("/food");
|
|
182
|
+
expect(result.router).toBeDefined();
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("returns express.Router when no path is provided", () => {
|
|
186
|
+
const result = modelRouter(FoodModel, {
|
|
187
|
+
permissions: {
|
|
188
|
+
create: [Permissions.IsAny],
|
|
189
|
+
delete: [Permissions.IsAny],
|
|
190
|
+
list: [Permissions.IsAny],
|
|
191
|
+
read: [Permissions.IsAny],
|
|
192
|
+
update: [Permissions.IsAny],
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// Should be a regular router (function), not a ModelRouterRegistration
|
|
197
|
+
expect(typeof result).toBe("function");
|
|
198
|
+
expect((result as any).__type).toBeUndefined();
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
});
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import * as Sentry from "@sentry/bun";
|
|
2
|
+
import openapi from "@wesleytodd/openapi";
|
|
3
|
+
import cors from "cors";
|
|
4
|
+
import express from "express";
|
|
5
|
+
import qs from "qs";
|
|
6
|
+
|
|
7
|
+
import type {ModelRouterRegistration} from "./api";
|
|
8
|
+
import {addAuthRoutes, addMeRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
|
|
9
|
+
import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "./errors";
|
|
10
|
+
import {type AuthOptions, logRequests} from "./expressServer";
|
|
11
|
+
import {addGitHubAuthRoutes, type GitHubAuthOptions, setupGitHubAuth} from "./githubAuth";
|
|
12
|
+
import {type LoggingOptions, logger, setupLogging} from "./logger";
|
|
13
|
+
import {openApiEtagMiddleware} from "./openApiEtag";
|
|
14
|
+
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
15
|
+
|
|
16
|
+
type CorsOrigin =
|
|
17
|
+
| string
|
|
18
|
+
| boolean
|
|
19
|
+
| RegExp
|
|
20
|
+
| Array<boolean | string | RegExp>
|
|
21
|
+
| ((
|
|
22
|
+
requestOrigin: string | undefined,
|
|
23
|
+
callback: (
|
|
24
|
+
err: Error | null,
|
|
25
|
+
origin?: boolean | string | RegExp | Array<boolean | string | RegExp>
|
|
26
|
+
) => void
|
|
27
|
+
) => void);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Configuration options for TerrenoApp.
|
|
31
|
+
*/
|
|
32
|
+
export interface TerrenoAppOptions {
|
|
33
|
+
/** Mongoose User model with passport-local-mongoose plugin */
|
|
34
|
+
userModel: UserMongooseModel;
|
|
35
|
+
/** CORS origin configuration (default: "*") */
|
|
36
|
+
corsOrigin?: CorsOrigin;
|
|
37
|
+
/** Logging configuration options */
|
|
38
|
+
loggingOptions?: LoggingOptions;
|
|
39
|
+
/** Authentication configuration options */
|
|
40
|
+
authOptions?: AuthOptions;
|
|
41
|
+
/** GitHub OAuth configuration (enables GitHub authentication if provided) */
|
|
42
|
+
githubAuth?: GitHubAuthOptions;
|
|
43
|
+
/** Skip calling app.listen() in start() method (useful for testing) */
|
|
44
|
+
skipListen?: boolean;
|
|
45
|
+
/** Sentry configuration options */
|
|
46
|
+
sentryOptions?: Sentry.BunOptions;
|
|
47
|
+
/** Maximum number of array items in query parameters (default: 200) */
|
|
48
|
+
arrayLimit?: number;
|
|
49
|
+
/** Whether to log all incoming requests (default: true) */
|
|
50
|
+
logRequests?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Fluent API for building Express applications with Terreno framework.
|
|
55
|
+
*
|
|
56
|
+
* TerrenoApp provides an alternative to `setupServer` using a registration
|
|
57
|
+
* pattern instead of callbacks. Build applications by registering model
|
|
58
|
+
* routers and plugins, then calling `start()` to begin listening.
|
|
59
|
+
*
|
|
60
|
+
* The middleware stack is configured in this order:
|
|
61
|
+
* 1. CORS
|
|
62
|
+
* 2. Custom middleware (via addMiddleware)
|
|
63
|
+
* 3. JSON body parser
|
|
64
|
+
* 4. Auth routes (/auth/login, /auth/signup, etc.)
|
|
65
|
+
* 5. JWT authentication setup
|
|
66
|
+
* 6. Request logging
|
|
67
|
+
* 7. Sentry scopes
|
|
68
|
+
* 8. OpenAPI middleware
|
|
69
|
+
* 9. /auth/me routes
|
|
70
|
+
* 10. GitHub OAuth routes (if enabled)
|
|
71
|
+
* 11. Registered model routers and plugins
|
|
72
|
+
* 12. Error handling middleware
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```typescript
|
|
76
|
+
* // Basic usage with model routers
|
|
77
|
+
* const todoRouter = modelRouter("/todos", Todo, {
|
|
78
|
+
* permissions: { list: [Permissions.IsAuthenticated], ... },
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* const app = new TerrenoApp({ userModel: User })
|
|
82
|
+
* .register(todoRouter)
|
|
83
|
+
* .register(new HealthApp())
|
|
84
|
+
* .start();
|
|
85
|
+
* ```
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* // With custom middleware
|
|
90
|
+
* const app = new TerrenoApp({
|
|
91
|
+
* userModel: User,
|
|
92
|
+
* corsOrigin: ["https://app.example.com"],
|
|
93
|
+
* loggingOptions: { logRequests: true },
|
|
94
|
+
* githubAuth: {
|
|
95
|
+
* clientId: process.env.GITHUB_CLIENT_ID!,
|
|
96
|
+
* clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
97
|
+
* callbackURL: process.env.GITHUB_CALLBACK_URL!,
|
|
98
|
+
* },
|
|
99
|
+
* })
|
|
100
|
+
* .addMiddleware((req, res, next) => {
|
|
101
|
+
* res.setHeader("X-Custom-Header", "value");
|
|
102
|
+
* next();
|
|
103
|
+
* })
|
|
104
|
+
* .register(todoRouter)
|
|
105
|
+
* .register(userRouter)
|
|
106
|
+
* .start();
|
|
107
|
+
* ```
|
|
108
|
+
*
|
|
109
|
+
* @see setupServer for the callback-based alternative
|
|
110
|
+
* @see TerrenoPlugin for creating reusable plugins
|
|
111
|
+
* @see modelRouter for creating CRUD route registrations
|
|
112
|
+
*/
|
|
113
|
+
export class TerrenoApp {
|
|
114
|
+
private options: TerrenoAppOptions;
|
|
115
|
+
private registrations: (ModelRouterRegistration | TerrenoPlugin)[] = [];
|
|
116
|
+
private middlewareFns: (express.RequestHandler | ((app: express.Application) => void))[] = [];
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Create a new TerrenoApp builder.
|
|
120
|
+
*
|
|
121
|
+
* @param options - Application configuration options including user model and auth settings
|
|
122
|
+
*/
|
|
123
|
+
constructor(options: TerrenoAppOptions) {
|
|
124
|
+
this.options = options;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Register a model router or plugin with the application.
|
|
129
|
+
*
|
|
130
|
+
* Model routers are created with `modelRouter("/path", Model, options)` and
|
|
131
|
+
* provide CRUD endpoints. Plugins implement `TerrenoPlugin` interface and
|
|
132
|
+
* can register custom routes and middleware.
|
|
133
|
+
*
|
|
134
|
+
* Registrations are mounted in the order they are added.
|
|
135
|
+
*
|
|
136
|
+
* @param registration - A ModelRouterRegistration from modelRouter() or a TerrenoPlugin instance
|
|
137
|
+
* @returns This TerrenoApp instance for method chaining
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* const todoRouter = modelRouter("/todos", Todo, options);
|
|
142
|
+
* const healthPlugin = new HealthApp({ path: "/health" });
|
|
143
|
+
*
|
|
144
|
+
* app.register(todoRouter).register(healthPlugin);
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
register(registration: ModelRouterRegistration | TerrenoPlugin): this {
|
|
148
|
+
this.registrations.push(registration);
|
|
149
|
+
return this;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Add custom Express middleware to the application.
|
|
154
|
+
*
|
|
155
|
+
* Middleware is added BEFORE JSON body parsing and authentication setup,
|
|
156
|
+
* allowing you to modify incoming requests early in the middleware stack.
|
|
157
|
+
*
|
|
158
|
+
* @param fn - Express middleware function or a function that configures the app
|
|
159
|
+
* @returns This TerrenoApp instance for method chaining
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```typescript
|
|
163
|
+
* app.addMiddleware((req, res, next) => {
|
|
164
|
+
* res.setHeader("X-Request-ID", req.id);
|
|
165
|
+
* next();
|
|
166
|
+
* });
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
addMiddleware(fn: express.RequestHandler | ((app: express.Application) => void)): this {
|
|
170
|
+
this.middlewareFns.push(fn);
|
|
171
|
+
return this;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Build the Express application without starting the server.
|
|
176
|
+
*
|
|
177
|
+
* Configures the complete middleware stack including:
|
|
178
|
+
* - CORS, JSON parsing, authentication, logging, Sentry, OpenAPI
|
|
179
|
+
* - All registered model routers and plugins
|
|
180
|
+
* - Error handling middleware
|
|
181
|
+
*
|
|
182
|
+
* Use this method when you need the Express app instance for testing
|
|
183
|
+
* or custom server setup. For normal use, call `start()` instead.
|
|
184
|
+
*
|
|
185
|
+
* @returns Configured Express application instance
|
|
186
|
+
*
|
|
187
|
+
* @example
|
|
188
|
+
* ```typescript
|
|
189
|
+
* const app = new TerrenoApp({ userModel: User })
|
|
190
|
+
* .register(todoRouter)
|
|
191
|
+
* .build();
|
|
192
|
+
*
|
|
193
|
+
* // Use app for testing with supertest
|
|
194
|
+
* await request(app).get("/todos").expect(200);
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
build(): express.Application {
|
|
198
|
+
setupLogging(this.options.loggingOptions);
|
|
199
|
+
|
|
200
|
+
const app = express();
|
|
201
|
+
const options = this.options;
|
|
202
|
+
|
|
203
|
+
app.set("query parser", (str: string) =>
|
|
204
|
+
qs.parse(str, {arrayLimit: options.arrayLimit ?? 200})
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
app.use(cors({origin: options.corsOrigin ?? "*"}));
|
|
208
|
+
|
|
209
|
+
// Apply custom middleware before JSON parsing
|
|
210
|
+
for (const fn of this.middlewareFns) {
|
|
211
|
+
if (fn.length <= 3) {
|
|
212
|
+
// express.RequestHandler (req, res, next)
|
|
213
|
+
app.use(fn as express.RequestHandler);
|
|
214
|
+
} else {
|
|
215
|
+
// Function that receives the app
|
|
216
|
+
(fn as (app: express.Application) => void)(app);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
app.use(express.json());
|
|
221
|
+
|
|
222
|
+
// Auth routes (login/signup/refresh_token) before JWT middleware
|
|
223
|
+
addAuthRoutes(app, options.userModel as any, options.authOptions);
|
|
224
|
+
setupAuth(app as any, options.userModel as any);
|
|
225
|
+
|
|
226
|
+
if (options.logRequests !== false) {
|
|
227
|
+
app.use(logRequests);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Store logging options on the response locals
|
|
231
|
+
app.use((_req, res, next) => {
|
|
232
|
+
res.locals.loggingOptions = options.loggingOptions;
|
|
233
|
+
next();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// Sentry scopes
|
|
237
|
+
app.all("*", (req: any, _res: any, next: any) => {
|
|
238
|
+
const transactionId = req.header("X-Transaction-ID");
|
|
239
|
+
const sessionId = req.header("X-Session-ID");
|
|
240
|
+
if (transactionId) {
|
|
241
|
+
Sentry.getCurrentScope().setTag("transaction_id", transactionId);
|
|
242
|
+
}
|
|
243
|
+
if (sessionId) {
|
|
244
|
+
Sentry.getCurrentScope().setTag("session_id", sessionId);
|
|
245
|
+
}
|
|
246
|
+
if (req.user?._id) {
|
|
247
|
+
Sentry.getCurrentScope().setTag("user", req.user._id);
|
|
248
|
+
}
|
|
249
|
+
next();
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// OpenAPI
|
|
253
|
+
app.use(openApiEtagMiddleware);
|
|
254
|
+
const oapi = openapi({
|
|
255
|
+
info: {
|
|
256
|
+
description: "Generated docs from an Express api",
|
|
257
|
+
title: "Express Application",
|
|
258
|
+
version: "1.0.0",
|
|
259
|
+
},
|
|
260
|
+
openapi: "3.0.0",
|
|
261
|
+
});
|
|
262
|
+
app.use(oapi);
|
|
263
|
+
|
|
264
|
+
if (process.env.ENABLE_SWAGGER === "true") {
|
|
265
|
+
app.use("/swagger", oapi.swaggerui());
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
addMeRoutes(app, options.userModel as any, options.authOptions);
|
|
269
|
+
|
|
270
|
+
// GitHub OAuth
|
|
271
|
+
if (options.githubAuth) {
|
|
272
|
+
setupGitHubAuth(app, options.userModel as any, options.githubAuth);
|
|
273
|
+
addGitHubAuthRoutes(app, options.userModel as any, options.githubAuth, options.authOptions);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Mount registered model routers and plugins
|
|
277
|
+
for (const registration of this.registrations) {
|
|
278
|
+
if (this.isModelRouterRegistration(registration)) {
|
|
279
|
+
app.use(registration.path, registration.router);
|
|
280
|
+
} else {
|
|
281
|
+
registration.register(app);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Inject openApi into model router options for registered routers
|
|
286
|
+
// The openApi middleware handles this via the oapi instance already mounted on the app
|
|
287
|
+
|
|
288
|
+
Sentry.setupExpressErrorHandler(app);
|
|
289
|
+
|
|
290
|
+
// Error middleware
|
|
291
|
+
app.use(apiUnauthorizedMiddleware);
|
|
292
|
+
app.use(apiErrorMiddleware);
|
|
293
|
+
|
|
294
|
+
app.use(function onError(err: any, _req: any, res: any, _next: any) {
|
|
295
|
+
logger.error(`Fallthrough error: ${err}${err?.stack ? `\n${err.stack}` : ""}}`);
|
|
296
|
+
Sentry.captureException(err);
|
|
297
|
+
res.statusCode = 500;
|
|
298
|
+
res.end(`${res.sentry}\n`);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
return app;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Build the Express application and start listening on the configured port.
|
|
306
|
+
*
|
|
307
|
+
* Calls `build()` to configure the application, then starts an HTTP server
|
|
308
|
+
* listening on the port specified by the `PORT` environment variable (default: 9000).
|
|
309
|
+
* If `skipListen` option is true, the app is built but the server is not started.
|
|
310
|
+
*
|
|
311
|
+
* @returns Configured Express application instance
|
|
312
|
+
*
|
|
313
|
+
* @throws Process exits with code 1 if the server fails to start
|
|
314
|
+
*
|
|
315
|
+
* @example
|
|
316
|
+
* ```typescript
|
|
317
|
+
* // Start server on port 3000
|
|
318
|
+
* process.env.PORT = "3000";
|
|
319
|
+
* const app = new TerrenoApp({ userModel: User })
|
|
320
|
+
* .register(todoRouter)
|
|
321
|
+
* .start();
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
start(): express.Application {
|
|
325
|
+
const app = this.build();
|
|
326
|
+
|
|
327
|
+
if (!this.options.skipListen) {
|
|
328
|
+
const port = process.env.PORT || "9000";
|
|
329
|
+
try {
|
|
330
|
+
app.listen(port, () => {
|
|
331
|
+
logger.info(`Listening on port ${port}`);
|
|
332
|
+
});
|
|
333
|
+
} catch (error) {
|
|
334
|
+
logger.error(`Error trying to start HTTP server: ${error}\n${(error as any).stack}`);
|
|
335
|
+
process.exit(1);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
return app;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private isModelRouterRegistration(
|
|
343
|
+
registration: ModelRouterRegistration | TerrenoPlugin
|
|
344
|
+
): registration is ModelRouterRegistration {
|
|
345
|
+
return (registration as ModelRouterRegistration).__type === "modelRouter";
|
|
346
|
+
}
|
|
347
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Interface for plugins that can be registered with TerrenoApp.
|
|
5
|
+
*
|
|
6
|
+
* Implement this interface to create reusable plugins that encapsulate
|
|
7
|
+
* routes, middleware, or other Express application setup. Plugins are
|
|
8
|
+
* registered via `TerrenoApp.register()` and are mounted after core
|
|
9
|
+
* authentication and OpenAPI middleware.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* class MyPlugin implements TerrenoPlugin {
|
|
14
|
+
* register(app: express.Application): void {
|
|
15
|
+
* app.get("/my-route", (req, res) => {
|
|
16
|
+
* res.json({ status: "ok" });
|
|
17
|
+
* });
|
|
18
|
+
* }
|
|
19
|
+
* }
|
|
20
|
+
*
|
|
21
|
+
* const app = new TerrenoApp({ userModel: User })
|
|
22
|
+
* .register(new MyPlugin())
|
|
23
|
+
* .start();
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* @see TerrenoApp for the application builder that consumes plugins
|
|
27
|
+
* @see HealthApp for a built-in plugin example
|
|
28
|
+
*/
|
|
29
|
+
export interface TerrenoPlugin {
|
|
30
|
+
/**
|
|
31
|
+
* Register routes and middleware with the Express application.
|
|
32
|
+
*
|
|
33
|
+
* Called during `TerrenoApp.build()` after core middleware has been
|
|
34
|
+
* configured but before error handling middleware is added.
|
|
35
|
+
*
|
|
36
|
+
* @param app - The Express application instance to register with
|
|
37
|
+
*/
|
|
38
|
+
register(app: express.Application): void;
|
|
39
|
+
}
|