api-machine 1.3.0 → 2.0.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/CHANGELOG.md +1 -1
- package/LICENSE.md +20 -20
- package/README.md +275 -275
- package/authentication/authenticated-request.d.ts +5 -0
- package/authentication/authentication-scheme.d.ts +8 -1
- package/authentication/authentication-scheme.js +46 -4
- package/authentication/authentication-scheme.js.map +1 -1
- package/authentication/index.d.ts +2 -2
- package/authentication/index.js +2 -1
- package/authentication/index.js.map +1 -1
- package/authentication/schemes/bearer-authentication-scheme.d.ts +5 -4
- package/authentication/schemes/bearer-authentication-scheme.js +3 -1
- package/authentication/schemes/bearer-authentication-scheme.js.map +1 -1
- package/authentication/schemes/client-credentials-oauth2-scheme.d.ts +64 -0
- package/authentication/schemes/client-credentials-oauth2-scheme.js +99 -0
- package/authentication/schemes/client-credentials-oauth2-scheme.js.map +1 -0
- package/authorization/authorization.d.ts +16 -0
- package/authorization/authorization.js +3 -0
- package/authorization/authorization.js.map +1 -0
- package/authorization/index.d.ts +1 -0
- package/authorization/index.js +5 -0
- package/authorization/index.js.map +1 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/index.js.map +1 -1
- package/package.json +2 -1
- package/router/base.d.ts +10 -0
- package/router/base.js +32 -3
- package/router/base.js.map +1 -1
- package/router/endpoint.d.ts +3 -2
- package/router/endpoint.js +33 -0
- package/router/endpoint.js.map +1 -1
- package/router/endpoints/health-check-endpoint.js +2 -0
- package/router/endpoints/health-check-endpoint.js.map +1 -1
- package/router/index.d.ts +1 -0
- package/router/index.js +5 -1
- package/router/index.js.map +1 -1
- package/server/server-options.d.ts +7 -0
- package/server/server-options.js.map +1 -1
- package/server/server.d.ts +4 -0
- package/server/server.js +24 -0
- package/server/server.js.map +1 -1
- package/session/session.d.ts +2 -0
- package/di/container.d.ts +0 -31
- package/di/container.js +0 -57
- package/di/container.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
# api-machine - Changelog
|
|
1
|
+
# api-machine - Changelog
|
package/LICENSE.md
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
Copyright (c) 2022 api-machine and others
|
|
2
|
-
|
|
3
|
-
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
-
a copy of this software and associated documentation files (the
|
|
5
|
-
"Software"), to deal in the Software without restriction, including
|
|
6
|
-
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
-
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
-
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
-
the following conditions:
|
|
10
|
-
|
|
11
|
-
The above copyright notice and this permission notice shall be
|
|
12
|
-
included in all copies or substantial portions of the Software.
|
|
13
|
-
|
|
14
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
-
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
-
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
-
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
-
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
-
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
1
|
+
Copyright (c) 2022 api-machine and others
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,275 +1,275 @@
|
|
|
1
|
-
# API-Machine
|
|
2
|
-
|
|
3
|
-
A lightweight, TypeScript-first REST API framework built on Express with a class-based routing architecture.
|
|
4
|
-
|
|
5
|
-
## Installation
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
npm i api-machine
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
## Features
|
|
12
|
-
|
|
13
|
-
- **TypeScript-First**: Fully typed API development with TypeScript
|
|
14
|
-
- **Self-documenting** - Automatically hosts Swagger & OpenAPI (when enabled)
|
|
15
|
-
- **Class-Based Architecture**: Organize your API with classes for servers, routers, and endpoints
|
|
16
|
-
- **Built on Express**: Leverages the power and ecosystem of Express.js
|
|
17
|
-
- **Secure by Default**: Automatic security headers and server fingerprinting protection
|
|
18
|
-
- **CORS Support**: Built-in CORS handling
|
|
19
|
-
- **Error Handling**: Automatic error handling with standardized responses
|
|
20
|
-
- **Configurable**: Flexible configuration for ports, payload sizes, and logging
|
|
21
|
-
|
|
22
|
-
## Quick Start
|
|
23
|
-
|
|
24
|
-
See the [Quick Start Example](examples/quick-start/) for a complete, runnable example.
|
|
25
|
-
|
|
26
|
-
Here's the basic structure:
|
|
27
|
-
|
|
28
|
-
### 1. Endpoints
|
|
29
|
-
|
|
30
|
-
```typescript
|
|
31
|
-
class HelloEndpoint extends BaseApiEndpoint {
|
|
32
|
-
override path = '/hello';
|
|
33
|
-
|
|
34
|
-
override async handle(request, response) {
|
|
35
|
-
return { message: 'Hello, World!' };
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
### 2. Routers
|
|
41
|
-
|
|
42
|
-
```typescript
|
|
43
|
-
class MyRouter extends BaseApiRouter {
|
|
44
|
-
override path = '/api';
|
|
45
|
-
|
|
46
|
-
override async routes() {
|
|
47
|
-
return [HelloEndpoint, /* UsersRouter */];
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
### 3. Servers
|
|
53
|
-
|
|
54
|
-
```typescript
|
|
55
|
-
class MyApiServer extends RestServer {
|
|
56
|
-
override router = MyRouter;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const server = new MyApiServer({
|
|
60
|
-
port: 4000,
|
|
61
|
-
swaggerEnabled: process.env?.NODE_ENV === 'development'
|
|
62
|
-
})
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
### Swagger
|
|
66
|
-
|
|
67
|
-
Navigate to http://localhost:4000/docs to browse your swagger API docs
|
|
68
|
-
|
|
69
|
-
## Examples
|
|
70
|
-
|
|
71
|
-
The [`examples/`](examples/) directory contains comprehensive examples:
|
|
72
|
-
|
|
73
|
-
- **[Quick Start](examples/quick-start/README.md)** - Basic server setup demonstrating the fundamental concepts
|
|
74
|
-
- Simple server, router, and endpoint structure
|
|
75
|
-
- Default GET endpoints
|
|
76
|
-
- Basic JSON responses
|
|
77
|
-
- Minimal configuration
|
|
78
|
-
|
|
79
|
-
- **[Complete Example](examples/complete-example/README.md)** - Advanced features and production patterns
|
|
80
|
-
- Full CRUD operations (GET, POST, PUT, DELETE)
|
|
81
|
-
- Route parameters and validation
|
|
82
|
-
- Error handling with proper status codes
|
|
83
|
-
- Custom logger configuration (ts-tiny-log)
|
|
84
|
-
- Express integration (headers, query params)
|
|
85
|
-
- Request body validation
|
|
86
|
-
- Structured error responses
|
|
87
|
-
|
|
88
|
-
### Example with Options
|
|
89
|
-
|
|
90
|
-
```typescript
|
|
91
|
-
const server = new MyApiServer({
|
|
92
|
-
port: 8080,
|
|
93
|
-
maxPayloadSizeMB: 20,
|
|
94
|
-
maxUrlEncodedSizeMB: 2,
|
|
95
|
-
log: myCustomLogger
|
|
96
|
-
});
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
#### Using Different HTTP Methods
|
|
100
|
-
|
|
101
|
-
api-machine provides convenience classes for each HTTP method with appropriate default status codes:
|
|
102
|
-
|
|
103
|
-
```typescript
|
|
104
|
-
// GET endpoint (200 OK by default)
|
|
105
|
-
class GetUsersEndpoint extends GetEndpoint {
|
|
106
|
-
override path = '/users';
|
|
107
|
-
|
|
108
|
-
async handle(request, response) {
|
|
109
|
-
return [{ id: 1, name: 'John' }];
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// POST endpoint
|
|
114
|
-
class CreateUserEndpoint extends PostEndpoint {
|
|
115
|
-
override path = '/users';
|
|
116
|
-
|
|
117
|
-
async handle(request, response) {
|
|
118
|
-
const newUser = {
|
|
119
|
-
id: Date.now(),
|
|
120
|
-
name: request.body.name
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
return newUser;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// PUT endpoint
|
|
128
|
-
class UpdateUserEndpoint extends PutEndpoint {
|
|
129
|
-
override path = '/users/:id';
|
|
130
|
-
|
|
131
|
-
async handle(request, response) {
|
|
132
|
-
const id = parseInt(request.params['id'], 10);
|
|
133
|
-
|
|
134
|
-
// Update entire user resource
|
|
135
|
-
return { id, ...request.body };
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// PATCH endpoint
|
|
140
|
-
class PatchUserEndpoint extends PatchEndpoint {
|
|
141
|
-
override path = '/users/:id';
|
|
142
|
-
|
|
143
|
-
async handle(request, response) {
|
|
144
|
-
const id = parseInt(request.params['id'], 10);
|
|
145
|
-
|
|
146
|
-
// Update only provided fields
|
|
147
|
-
return { id, ...request.body };
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// DELETE endpoint (204 No Content by default)
|
|
152
|
-
class DeleteUserEndpoint extends DeleteEndpoint {
|
|
153
|
-
override path = '/users/:id';
|
|
154
|
-
|
|
155
|
-
async handle(request, response) {
|
|
156
|
-
const id = parseInt(request.params['id'], 10);
|
|
157
|
-
|
|
158
|
-
// Deletion logic here
|
|
159
|
-
return {};
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
#### Pre-Built Endpoints
|
|
165
|
-
|
|
166
|
-
##### HealthCheckEndpoint
|
|
167
|
-
|
|
168
|
-
A ready-to-use health check endpoint that returns system status information. Simply include it in your router. For advanced usage, extending the health check with custom checks, and deployment examples (Kubernetes, Docker, monitoring), see the **[Health Check Endpoint Documentation](docs/health-check-endpoint.md)**.
|
|
169
|
-
|
|
170
|
-
## Error Handling
|
|
171
|
-
|
|
172
|
-
api-machine provides a comprehensive set of HTTP error classes for standardized error responses. All errors extend `HTTPError` and automatically format responses with proper status codes and headers.
|
|
173
|
-
|
|
174
|
-
```typescript
|
|
175
|
-
import { NotFoundError, BadRequestError, UnauthorizedError } from 'api-machine';
|
|
176
|
-
|
|
177
|
-
class GetUserEndpoint extends GetEndpoint {
|
|
178
|
-
override path = '/users/:id';
|
|
179
|
-
|
|
180
|
-
async handle(request, response) {
|
|
181
|
-
const id = parseInt(request.params['id'], 10);
|
|
182
|
-
const user = await findUser(id);
|
|
183
|
-
|
|
184
|
-
if (!user) {
|
|
185
|
-
throw new NotFoundError('User not found', {
|
|
186
|
-
details: { userId: id }
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return user;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
**Key Features:**
|
|
196
|
-
- Built-in error classes covering HTTP status codes 400-451
|
|
197
|
-
- Automatic JSON error responses with timestamps
|
|
198
|
-
- Support for custom headers (e.g., `WWW-Authenticate`, `Retry-After`)
|
|
199
|
-
- Optional `details` field for additional context
|
|
200
|
-
- User-provided headers override defaults
|
|
201
|
-
|
|
202
|
-
**Common Error Classes:**
|
|
203
|
-
- `BadRequestError` (400)
|
|
204
|
-
- `UnauthorizedError` (401)
|
|
205
|
-
- `ForbiddenError` (403)
|
|
206
|
-
- `NotFoundError` (404)
|
|
207
|
-
- `ConflictError` (409)
|
|
208
|
-
- `UnprocessableEntityError` (422)
|
|
209
|
-
- `TooManyRequestsError` (429)
|
|
210
|
-
|
|
211
|
-
For the complete list of error classes, usage examples, and custom error creation, see the **[HTTP Errors Documentation](docs/http-errors.md)**.
|
|
212
|
-
|
|
213
|
-
## Validation & Sanitization
|
|
214
|
-
|
|
215
|
-
api-machine supports request validation and sanitization using [valsan](https://www.npmjs.com/package/valsan). You can declare ObjectValSan members on your endpoint classes for `body`, `query`, `params`, or `headers`:
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
import { ObjectValSan, EmailValidator } from 'valsan';
|
|
219
|
-
import { NameValSan } from './examples/complete-example/users/name-valsan';
|
|
220
|
-
|
|
221
|
-
class CreateUserEndpoint extends PostEndpoint {
|
|
222
|
-
override path = '/users';
|
|
223
|
-
|
|
224
|
-
override body = new ObjectValSan({
|
|
225
|
-
schema: {
|
|
226
|
-
name: new NameValSan(),
|
|
227
|
-
email: new EmailValidator(),
|
|
228
|
-
}
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
async handle(request, response) {
|
|
232
|
-
// request.body is validated & sanitized
|
|
233
|
-
// ...
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
```
|
|
237
|
-
|
|
238
|
-
- If validation fails, a 400 error is returned with details.
|
|
239
|
-
- If validation succeeds, the sanitized values are available in `request.body`, `request.query`, etc.
|
|
240
|
-
|
|
241
|
-
You can create custom validators by extending `ComposedValSan` from valsan. See the [valsan documentation](../valsan/README.md) for more details.
|
|
242
|
-
|
|
243
|
-
## Authentication
|
|
244
|
-
|
|
245
|
-
api-machine provides a declarative authentication system with cascading support across server, router, and endpoint levels:
|
|
246
|
-
|
|
247
|
-
```typescript
|
|
248
|
-
class SecureRouter extends BaseApiRouter {
|
|
249
|
-
override path = '/api';
|
|
250
|
-
override authentication = new BearerAuthenticationScheme({
|
|
251
|
-
checkToken: async (token: string) => await validateToken(token),
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
async routes() {
|
|
255
|
-
return [ProtectedEndpoint];
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
```
|
|
259
|
-
|
|
260
|
-
**Key Features:**
|
|
261
|
-
- **Cascading authentication** - Server → Router → Endpoint priority
|
|
262
|
-
- **Bearer token support** - Built-in Bearer authentication scheme
|
|
263
|
-
- **OpenAPI integration** - Automatic security scheme generation
|
|
264
|
-
- **Public routes** - Set `authentication = null` to bypass parent auth
|
|
265
|
-
- **Custom schemes** - Extend `AuthenticationScheme` for custom auth
|
|
266
|
-
|
|
267
|
-
See **[Authentication Documentation](docs/authentication.md)** for complete usage, cascading examples, and custom authentication schemes.
|
|
268
|
-
|
|
269
|
-
## Middleware
|
|
270
|
-
|
|
271
|
-
Routers and endpoints support Express middleware for logging, validation, and more. See [Middleware Support](docs/middleware.md) for usage and examples.
|
|
272
|
-
|
|
273
|
-
## Contributing & Development
|
|
274
|
-
|
|
275
|
-
See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
|
|
1
|
+
# API-Machine
|
|
2
|
+
|
|
3
|
+
A lightweight, TypeScript-first REST API framework built on Express with a class-based routing architecture.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i api-machine
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **TypeScript-First**: Fully typed API development with TypeScript
|
|
14
|
+
- **Self-documenting** - Automatically hosts Swagger & OpenAPI (when enabled)
|
|
15
|
+
- **Class-Based Architecture**: Organize your API with classes for servers, routers, and endpoints
|
|
16
|
+
- **Built on Express**: Leverages the power and ecosystem of Express.js
|
|
17
|
+
- **Secure by Default**: Automatic security headers and server fingerprinting protection
|
|
18
|
+
- **CORS Support**: Built-in CORS handling
|
|
19
|
+
- **Error Handling**: Automatic error handling with standardized responses
|
|
20
|
+
- **Configurable**: Flexible configuration for ports, payload sizes, and logging
|
|
21
|
+
|
|
22
|
+
## Quick Start
|
|
23
|
+
|
|
24
|
+
See the [Quick Start Example](examples/quick-start/) for a complete, runnable example.
|
|
25
|
+
|
|
26
|
+
Here's the basic structure:
|
|
27
|
+
|
|
28
|
+
### 1. Endpoints
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
class HelloEndpoint extends BaseApiEndpoint {
|
|
32
|
+
override path = '/hello';
|
|
33
|
+
|
|
34
|
+
override async handle(request, response) {
|
|
35
|
+
return { message: 'Hello, World!' };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### 2. Routers
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
class MyRouter extends BaseApiRouter {
|
|
44
|
+
override path = '/api';
|
|
45
|
+
|
|
46
|
+
override async routes() {
|
|
47
|
+
return [HelloEndpoint, /* UsersRouter */];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 3. Servers
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
class MyApiServer extends RestServer {
|
|
56
|
+
override router = MyRouter;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const server = new MyApiServer({
|
|
60
|
+
port: 4000,
|
|
61
|
+
swaggerEnabled: process.env?.NODE_ENV === 'development'
|
|
62
|
+
})
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Swagger
|
|
66
|
+
|
|
67
|
+
Navigate to http://localhost:4000/docs to browse your swagger API docs
|
|
68
|
+
|
|
69
|
+
## Examples
|
|
70
|
+
|
|
71
|
+
The [`examples/`](examples/) directory contains comprehensive examples:
|
|
72
|
+
|
|
73
|
+
- **[Quick Start](examples/quick-start/README.md)** - Basic server setup demonstrating the fundamental concepts
|
|
74
|
+
- Simple server, router, and endpoint structure
|
|
75
|
+
- Default GET endpoints
|
|
76
|
+
- Basic JSON responses
|
|
77
|
+
- Minimal configuration
|
|
78
|
+
|
|
79
|
+
- **[Complete Example](examples/complete-example/README.md)** - Advanced features and production patterns
|
|
80
|
+
- Full CRUD operations (GET, POST, PUT, DELETE)
|
|
81
|
+
- Route parameters and validation
|
|
82
|
+
- Error handling with proper status codes
|
|
83
|
+
- Custom logger configuration (ts-tiny-log)
|
|
84
|
+
- Express integration (headers, query params)
|
|
85
|
+
- Request body validation
|
|
86
|
+
- Structured error responses
|
|
87
|
+
|
|
88
|
+
### Example with Options
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
const server = new MyApiServer({
|
|
92
|
+
port: 8080,
|
|
93
|
+
maxPayloadSizeMB: 20,
|
|
94
|
+
maxUrlEncodedSizeMB: 2,
|
|
95
|
+
log: myCustomLogger
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
#### Using Different HTTP Methods
|
|
100
|
+
|
|
101
|
+
api-machine provides convenience classes for each HTTP method with appropriate default status codes:
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// GET endpoint (200 OK by default)
|
|
105
|
+
class GetUsersEndpoint extends GetEndpoint {
|
|
106
|
+
override path = '/users';
|
|
107
|
+
|
|
108
|
+
async handle(request, response) {
|
|
109
|
+
return [{ id: 1, name: 'John' }];
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// POST endpoint
|
|
114
|
+
class CreateUserEndpoint extends PostEndpoint {
|
|
115
|
+
override path = '/users';
|
|
116
|
+
|
|
117
|
+
async handle(request, response) {
|
|
118
|
+
const newUser = {
|
|
119
|
+
id: Date.now(),
|
|
120
|
+
name: request.body.name
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
return newUser;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// PUT endpoint
|
|
128
|
+
class UpdateUserEndpoint extends PutEndpoint {
|
|
129
|
+
override path = '/users/:id';
|
|
130
|
+
|
|
131
|
+
async handle(request, response) {
|
|
132
|
+
const id = parseInt(request.params['id'], 10);
|
|
133
|
+
|
|
134
|
+
// Update entire user resource
|
|
135
|
+
return { id, ...request.body };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// PATCH endpoint
|
|
140
|
+
class PatchUserEndpoint extends PatchEndpoint {
|
|
141
|
+
override path = '/users/:id';
|
|
142
|
+
|
|
143
|
+
async handle(request, response) {
|
|
144
|
+
const id = parseInt(request.params['id'], 10);
|
|
145
|
+
|
|
146
|
+
// Update only provided fields
|
|
147
|
+
return { id, ...request.body };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// DELETE endpoint (204 No Content by default)
|
|
152
|
+
class DeleteUserEndpoint extends DeleteEndpoint {
|
|
153
|
+
override path = '/users/:id';
|
|
154
|
+
|
|
155
|
+
async handle(request, response) {
|
|
156
|
+
const id = parseInt(request.params['id'], 10);
|
|
157
|
+
|
|
158
|
+
// Deletion logic here
|
|
159
|
+
return {};
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
#### Pre-Built Endpoints
|
|
165
|
+
|
|
166
|
+
##### HealthCheckEndpoint
|
|
167
|
+
|
|
168
|
+
A ready-to-use health check endpoint that returns system status information. Simply include it in your router. For advanced usage, extending the health check with custom checks, and deployment examples (Kubernetes, Docker, monitoring), see the **[Health Check Endpoint Documentation](docs/health-check-endpoint.md)**.
|
|
169
|
+
|
|
170
|
+
## Error Handling
|
|
171
|
+
|
|
172
|
+
api-machine provides a comprehensive set of HTTP error classes for standardized error responses. All errors extend `HTTPError` and automatically format responses with proper status codes and headers.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { NotFoundError, BadRequestError, UnauthorizedError } from 'api-machine';
|
|
176
|
+
|
|
177
|
+
class GetUserEndpoint extends GetEndpoint {
|
|
178
|
+
override path = '/users/:id';
|
|
179
|
+
|
|
180
|
+
async handle(request, response) {
|
|
181
|
+
const id = parseInt(request.params['id'], 10);
|
|
182
|
+
const user = await findUser(id);
|
|
183
|
+
|
|
184
|
+
if (!user) {
|
|
185
|
+
throw new NotFoundError('User not found', {
|
|
186
|
+
details: { userId: id }
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return user;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
**Key Features:**
|
|
196
|
+
- Built-in error classes covering HTTP status codes 400-451
|
|
197
|
+
- Automatic JSON error responses with timestamps
|
|
198
|
+
- Support for custom headers (e.g., `WWW-Authenticate`, `Retry-After`)
|
|
199
|
+
- Optional `details` field for additional context
|
|
200
|
+
- User-provided headers override defaults
|
|
201
|
+
|
|
202
|
+
**Common Error Classes:**
|
|
203
|
+
- `BadRequestError` (400)
|
|
204
|
+
- `UnauthorizedError` (401)
|
|
205
|
+
- `ForbiddenError` (403)
|
|
206
|
+
- `NotFoundError` (404)
|
|
207
|
+
- `ConflictError` (409)
|
|
208
|
+
- `UnprocessableEntityError` (422)
|
|
209
|
+
- `TooManyRequestsError` (429)
|
|
210
|
+
|
|
211
|
+
For the complete list of error classes, usage examples, and custom error creation, see the **[HTTP Errors Documentation](docs/http-errors.md)**.
|
|
212
|
+
|
|
213
|
+
## Validation & Sanitization
|
|
214
|
+
|
|
215
|
+
api-machine supports request validation and sanitization using [valsan](https://www.npmjs.com/package/valsan). You can declare ObjectValSan members on your endpoint classes for `body`, `query`, `params`, or `headers`:
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { ObjectValSan, EmailValidator } from 'valsan';
|
|
219
|
+
import { NameValSan } from './examples/complete-example/users/name-valsan';
|
|
220
|
+
|
|
221
|
+
class CreateUserEndpoint extends PostEndpoint {
|
|
222
|
+
override path = '/users';
|
|
223
|
+
|
|
224
|
+
override body = new ObjectValSan({
|
|
225
|
+
schema: {
|
|
226
|
+
name: new NameValSan(),
|
|
227
|
+
email: new EmailValidator(),
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
async handle(request, response) {
|
|
232
|
+
// request.body is validated & sanitized
|
|
233
|
+
// ...
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
- If validation fails, a 400 error is returned with details.
|
|
239
|
+
- If validation succeeds, the sanitized values are available in `request.body`, `request.query`, etc.
|
|
240
|
+
|
|
241
|
+
You can create custom validators by extending `ComposedValSan` from valsan. See the [valsan documentation](../valsan/README.md) for more details.
|
|
242
|
+
|
|
243
|
+
## Authentication
|
|
244
|
+
|
|
245
|
+
api-machine provides a declarative authentication system with cascading support across server, router, and endpoint levels:
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
class SecureRouter extends BaseApiRouter {
|
|
249
|
+
override path = '/api';
|
|
250
|
+
override authentication = new BearerAuthenticationScheme({
|
|
251
|
+
checkToken: async (token: string) => await validateToken(token),
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
async routes() {
|
|
255
|
+
return [ProtectedEndpoint];
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
**Key Features:**
|
|
261
|
+
- **Cascading authentication** - Server → Router → Endpoint priority
|
|
262
|
+
- **Bearer token support** - Built-in Bearer authentication scheme
|
|
263
|
+
- **OpenAPI integration** - Automatic security scheme generation
|
|
264
|
+
- **Public routes** - Set `authentication = null` to bypass parent auth
|
|
265
|
+
- **Custom schemes** - Extend `AuthenticationScheme` for custom auth
|
|
266
|
+
|
|
267
|
+
See **[Authentication Documentation](docs/authentication.md)** for complete usage, cascading examples, and custom authentication schemes.
|
|
268
|
+
|
|
269
|
+
## Middleware
|
|
270
|
+
|
|
271
|
+
Routers and endpoints support Express middleware for logging, validation, and more. See [Middleware Support](docs/middleware.md) for usage and examples.
|
|
272
|
+
|
|
273
|
+
## Contributing & Development
|
|
274
|
+
|
|
275
|
+
See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
|
|
@@ -2,6 +2,7 @@ import { RequestHandler } from 'express';
|
|
|
2
2
|
import { SecuritySchemeObject, SecurityRequirementObject } from 'auto-oas/oas/v3.1';
|
|
3
3
|
import { ApiRequest, BaseApiRouter } from '../router';
|
|
4
4
|
import { SessionDriver } from '../session/session-driver';
|
|
5
|
+
import { AuthenticatedPrincipal, AuthenticatedRequest } from './authenticated-request';
|
|
5
6
|
import { AuthFlow } from './auth-flow';
|
|
6
7
|
import { ApiRoute } from '../router/base';
|
|
7
8
|
export interface AuthenticationSchemeOptions {
|
|
@@ -40,12 +41,17 @@ export declare abstract class AuthenticationScheme {
|
|
|
40
41
|
*/
|
|
41
42
|
abstract getMiddleware(): RequestHandler;
|
|
42
43
|
}
|
|
44
|
+
export interface AuthenticationProtectionResult {
|
|
45
|
+
allowed: boolean;
|
|
46
|
+
retryAfterSeconds?: number;
|
|
47
|
+
}
|
|
48
|
+
export declare function throwIfAuthenticationBlocked(result: AuthenticationProtectionResult): void;
|
|
43
49
|
export declare abstract class InlineAuthenticationScheme extends AuthenticationScheme {
|
|
44
50
|
abstract getCredentials(request: ApiRequest): unknown;
|
|
45
51
|
abstract authenticate(options: {
|
|
46
52
|
credentials: unknown;
|
|
47
53
|
request: ApiRequest;
|
|
48
|
-
}): Promise<void>;
|
|
54
|
+
}): Promise<void | AuthenticatedPrincipal>;
|
|
49
55
|
/**
|
|
50
56
|
* Generate the Express middleware that enforces this authentication
|
|
51
57
|
* The middleware should validate the authentication and throw appropriate
|
|
@@ -82,4 +88,5 @@ export declare abstract class SessionAuthenticationScheme extends Authentication
|
|
|
82
88
|
*/
|
|
83
89
|
getAuthRouter(basePath?: string): BaseApiRouter;
|
|
84
90
|
getMiddleware(): RequestHandler;
|
|
91
|
+
protected getSessionId(request: AuthenticatedRequest): string | undefined;
|
|
85
92
|
}
|