@antelopejs/interface-api-util 0.1.1 → 0.1.2
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/docs/1.introduction.md +190 -0
- package/package.json +8 -3
- package/skills/api-util-interface/SKILL.md +81 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# Interface API Util Documentation
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
Interface API Util provides utilities for validating API requests, rate limiting handlers, and returning structured HTTP error responses. The package exports `assert` for checking conditions, `assertValidation` for running input validators, and the `@RateLimit` decorator for throttling handlers. All of them surface failures as `HTTPResult` errors from `@antelopejs/interface-api`.
|
|
6
|
+
|
|
7
|
+
## Getting Started
|
|
8
|
+
|
|
9
|
+
Install the package in your project:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @antelopejs/interface-api-util
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## `assert`
|
|
16
|
+
|
|
17
|
+
The `assert` function checks whether a condition is truthy. If the condition is falsy, it throws an `HTTPResult` with the specified HTTP status code and error message.
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
function assert<T>(condition: T, code: number, message: string): asserts condition;
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
| Parameter | Type | Description |
|
|
24
|
+
| ----------- | -------- | ---------------------------------------------------- |
|
|
25
|
+
| `condition` | `T` | The value to check (falsy values trigger the error) |
|
|
26
|
+
| `code` | `number` | HTTP status code for the error response |
|
|
27
|
+
| `message` | `string` | Error message included in the response body |
|
|
28
|
+
|
|
29
|
+
The function uses TypeScript's `asserts` keyword, so the compiler narrows the type of `condition` to truthy after the call.
|
|
30
|
+
|
|
31
|
+
### Check that a resource exists
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { assert } from "@antelopejs/interface-api-util";
|
|
35
|
+
import { HTTPResult } from "@antelopejs/interface-api";
|
|
36
|
+
|
|
37
|
+
async function getUser(id: string) {
|
|
38
|
+
const user = await findUser(id);
|
|
39
|
+
assert(user, 404, "User not found");
|
|
40
|
+
|
|
41
|
+
// TypeScript knows `user` is defined here
|
|
42
|
+
return new HTTPResult(200, user);
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Validate permissions
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { assert } from "@antelopejs/interface-api-util";
|
|
50
|
+
import { HTTPResult } from "@antelopejs/interface-api";
|
|
51
|
+
|
|
52
|
+
async function deletePost(postId: string, currentUserId: string) {
|
|
53
|
+
const post = await findPost(postId);
|
|
54
|
+
assert(post, 404, "Post not found");
|
|
55
|
+
assert(post.authorId === currentUserId, 403, "Not authorized to delete this post");
|
|
56
|
+
|
|
57
|
+
await removePost(postId);
|
|
58
|
+
return new HTTPResult(200, { deleted: true });
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## `assertValidation`
|
|
63
|
+
|
|
64
|
+
The `assertValidation` function runs a validator on an input value. If the validator throws, `assertValidation` catches the error and throws an `HTTPResult` instead.
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
function assertValidation<T>(
|
|
68
|
+
body: unknown,
|
|
69
|
+
validator: (body: unknown) => T,
|
|
70
|
+
errorFunc?: (err: unknown) => unknown,
|
|
71
|
+
code?: number,
|
|
72
|
+
): T;
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
| Parameter | Type | Default | Description |
|
|
76
|
+
| ----------- | ----------------------------- | ------- | ------------------------------------------------------- |
|
|
77
|
+
| `body` | `unknown` | | The input value to validate |
|
|
78
|
+
| `validator` | `(body: unknown) => T` | | A function that returns the validated value or throws |
|
|
79
|
+
| `errorFunc` | `(err: unknown) => unknown` | | Optional error transformer for customizing the response |
|
|
80
|
+
| `code` | `number` | `400` | HTTP status code for the error response |
|
|
81
|
+
|
|
82
|
+
The function returns the validated value on success. On failure, it throws an `HTTPResult` whose body is either the result of `errorFunc` or the stringified error.
|
|
83
|
+
|
|
84
|
+
### Validate with Zod
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
import { assertValidation } from "@antelopejs/interface-api-util";
|
|
88
|
+
import * as z from "zod";
|
|
89
|
+
|
|
90
|
+
const createUserSchema = z.object({
|
|
91
|
+
name: z.string().min(1),
|
|
92
|
+
email: z.string().email(),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
function createUser(requestBody: unknown) {
|
|
96
|
+
const { name, email } = assertValidation(requestBody, createUserSchema.parse);
|
|
97
|
+
|
|
98
|
+
// `name` and `email` are typed strings here
|
|
99
|
+
return saveUser({ name, email });
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Custom error formatting
|
|
104
|
+
|
|
105
|
+
Pass an `errorFunc` to control the error response body.
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
import { assertValidation } from "@antelopejs/interface-api-util";
|
|
109
|
+
import * as z from "zod";
|
|
110
|
+
|
|
111
|
+
const schema = z.object({ age: z.number().min(18) });
|
|
112
|
+
|
|
113
|
+
function validateAge(requestBody: unknown) {
|
|
114
|
+
return assertValidation(
|
|
115
|
+
requestBody,
|
|
116
|
+
schema.parse,
|
|
117
|
+
(err) => {
|
|
118
|
+
if (err instanceof z.ZodError) {
|
|
119
|
+
return { errors: err.errors.map((e) => e.message) };
|
|
120
|
+
}
|
|
121
|
+
return { errors: [String(err)] };
|
|
122
|
+
},
|
|
123
|
+
422,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## `RateLimit`
|
|
129
|
+
|
|
130
|
+
The `@RateLimit` decorator caps how often a route handler can be called. It counts requests per client in a fixed time window (in-memory, per process). Successful responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` (a UNIX epoch-seconds timestamp) so clients can self-pace. Once the count exceeds `limit` within `windowMs`, the handler instead throws an `HTTPResult` with status `429` (adding a `Retry-After` header) without running.
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
function RateLimit(
|
|
134
|
+
limit: number,
|
|
135
|
+
windowMs: number,
|
|
136
|
+
options?: RateLimitOptions,
|
|
137
|
+
): MethodDecorator;
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
| Parameter | Type | Description |
|
|
141
|
+
| ---------- | ------------------ | -------------------------------------------------------- |
|
|
142
|
+
| `limit` | `number` | Maximum number of requests allowed per window |
|
|
143
|
+
| `windowMs` | `number` | Window duration in milliseconds |
|
|
144
|
+
| `options` | `RateLimitOptions` | Optional custom key function and `429` response body |
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
interface RateLimitOptions {
|
|
148
|
+
key?: (context: RequestContext) => string | null | undefined;
|
|
149
|
+
message?: string;
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
By default, requests are counted per client IP (`context.rawRequest.socket.remoteAddress`). Provide `options.key` to count by user id, API key, or a forwarded header instead. If the custom key function returns a falsy value (for example a missing route parameter), the limiter falls back to the client IP rather than collapsing every such request into one shared bucket.
|
|
154
|
+
|
|
155
|
+
> **Ordering matters.** Place `@RateLimit` **directly beneath** the route decorator (`@Get`, `@Post`, …). The route decorator captures the handler's parameters when it is applied, so a `@RateLimit` above it would be ignored — this is detected at startup and throws, rather than silently leaving the route unprotected.
|
|
156
|
+
|
|
157
|
+
### Limit by client IP
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { RateLimit } from "@antelopejs/interface-api-util";
|
|
161
|
+
import { Controller, Get, HTTPResult } from "@antelopejs/interface-api";
|
|
162
|
+
|
|
163
|
+
class UsersController extends Controller("users") {
|
|
164
|
+
@Get()
|
|
165
|
+
@RateLimit(100, 60_000)
|
|
166
|
+
list() {
|
|
167
|
+
return new HTTPResult(200, { users: [] });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### Limit by a custom key
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { RateLimit } from "@antelopejs/interface-api-util";
|
|
176
|
+
import { Controller, Post, HTTPResult } from "@antelopejs/interface-api";
|
|
177
|
+
|
|
178
|
+
class AuthController extends Controller("auth") {
|
|
179
|
+
@Post("login")
|
|
180
|
+
@RateLimit(5, 60_000, {
|
|
181
|
+
key: (ctx) => ctx.routeParameters.tenant,
|
|
182
|
+
message: "Too many login attempts, slow down",
|
|
183
|
+
})
|
|
184
|
+
login() {
|
|
185
|
+
return new HTTPResult(200, { ok: true });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Counts are kept in process memory, so they are not shared across instances and reset on restart. Elapsed windows are pruned periodically, so the store is bounded by the number of distinct keys seen within a single window rather than growing forever. For distributed limits, key by a stable identifier and enforce limits in a shared store at the edge. Behind a proxy, the socket address is the proxy's — supply `options.key` to read a forwarded header, but only trust the hop your proxy sets (a raw client-supplied `X-Forwarded-For` is spoofable and can be used to evade or to inflate the key cardinality).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@antelopejs/interface-api-util",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "AntelopeJS utility functions for API request validation and error handling",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"antelopejs",
|
|
@@ -17,7 +17,9 @@
|
|
|
17
17
|
"main": "dist/index.js",
|
|
18
18
|
"types": "dist/index.d.ts",
|
|
19
19
|
"files": [
|
|
20
|
-
"dist"
|
|
20
|
+
"dist",
|
|
21
|
+
"docs",
|
|
22
|
+
"skills"
|
|
21
23
|
],
|
|
22
24
|
"exports": {
|
|
23
25
|
".": {
|
|
@@ -36,7 +38,10 @@
|
|
|
36
38
|
"test": "pnpm run build && ajs module test ."
|
|
37
39
|
},
|
|
38
40
|
"antelopeJs": {
|
|
39
|
-
"test": "src/antelope.test.ts"
|
|
41
|
+
"test": "src/antelope.test.ts",
|
|
42
|
+
"skills": [
|
|
43
|
+
"./skills"
|
|
44
|
+
]
|
|
40
45
|
},
|
|
41
46
|
"devDependencies": {
|
|
42
47
|
"@antelopejs/interface-api": "^0.0.5",
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: api-util-interface
|
|
3
|
+
description: Provides handler-side utilities for AntelopeJS APIs built on @antelopejs/interface-api - assert and assertValidation turn failed checks into HTTPResult error responses, and the @RateLimit method decorator adds fixed-window throttling with 429/Retry-After and X-RateLimit headers. Use when code imports from "@antelopejs/interface-api-util", when validating request bodies (e.g. with a Zod schema) inside @Get/@Post handlers, when returning 400/404/403-style errors from API controllers, or when asked to rate limit a route.
|
|
4
|
+
category: antelopejs-interface
|
|
5
|
+
tags: [antelopejs, api, validation, rate-limit, http]
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# API Util Interface
|
|
9
|
+
|
|
10
|
+
Consumer-side helper library for AntelopeJS API modules. It is NOT an interface proxy itself:
|
|
11
|
+
nothing here crosses an interface boundary, so there is no `ImplementInterface` side. Everything
|
|
12
|
+
builds on its peer dependencies `@antelopejs/interface-api` (for `HTTPResult`, `RequestContext`,
|
|
13
|
+
controller metadata) and `@antelopejs/interface-core` (decorator machinery). All failures surface
|
|
14
|
+
as thrown `HTTPResult` values, which the API interface converts into HTTP responses.
|
|
15
|
+
|
|
16
|
+
## Imports
|
|
17
|
+
|
|
18
|
+
The package has a single export subpath (root only):
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { assert, assertValidation, RateLimit, type RateLimitOptions } from "@antelopejs/interface-api-util";
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`hitWindow`, `pruneExpired`, and `resolveKey` are also exported but marked `@internal` (rate-limit
|
|
25
|
+
plumbing, exposed for tests) — do not reach for them in application code.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { Controller, Get, Post, HTTPResult, Parameter, RawBody } from "@antelopejs/interface-api";
|
|
31
|
+
import { assert, assertValidation, RateLimit } from "@antelopejs/interface-api-util";
|
|
32
|
+
import * as z from "zod";
|
|
33
|
+
|
|
34
|
+
const createMemberSchema = z.object({ fullName: z.string().min(1), email: z.string().email() });
|
|
35
|
+
|
|
36
|
+
class MembersController extends Controller("members") {
|
|
37
|
+
@Get(":id")
|
|
38
|
+
@RateLimit(100, 60_000)
|
|
39
|
+
async get(@Parameter("id") id: string) {
|
|
40
|
+
const member = await findMember(id);
|
|
41
|
+
assert(member, 404, "Member not found"); // narrows `member` to non-falsy below
|
|
42
|
+
return new HTTPResult(200, member);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
@Post()
|
|
46
|
+
async create(@RawBody() body: Buffer) {
|
|
47
|
+
const { fullName, email } = assertValidation(body, (b) => createMemberSchema.parse(JSON.parse((b as Buffer).toString())));
|
|
48
|
+
return new HTTPResult(201, await saveMember({ fullName, email }));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- `assert(condition, code, message)` — throws `new HTTPResult(code, message)` when falsy; uses
|
|
54
|
+
TypeScript `asserts condition`, so the compiler narrows after the call.
|
|
55
|
+
- `assertValidation(body, validator, errorFunc?, code = 400)` — returns the validator's result;
|
|
56
|
+
if the validator throws, rethrows an `HTTPResult` whose body is `errorFunc(err)` if provided,
|
|
57
|
+
otherwise `String(err)`.
|
|
58
|
+
- `RateLimit(limit, windowMs, options?)` — fixed-window counter per key; over-limit requests throw
|
|
59
|
+
a 429 `HTTPResult` (with `Retry-After`) before the handler runs. Successful responses get
|
|
60
|
+
`X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` (epoch seconds) headers.
|
|
61
|
+
|
|
62
|
+
## Gotchas
|
|
63
|
+
|
|
64
|
+
- Decorator ordering: `@RateLimit` must sit directly BENEATH the route decorator
|
|
65
|
+
(`@Get`, `@Post`, ...). Placed above it, the guard would be ignored — this is detected at
|
|
66
|
+
decoration time and throws an `Error` at startup instead of silently unprotecting the route.
|
|
67
|
+
- Rate-limit keys default to the client IP (`context.rawRequest.socket.remoteAddress`). Behind a
|
|
68
|
+
proxy that is the proxy's address — supply `options.key` reading a trusted forwarded header. If
|
|
69
|
+
the custom `key` function returns a falsy value, the limiter falls back to the client IP rather
|
|
70
|
+
than merging those requests into one shared bucket.
|
|
71
|
+
- Counts live in process memory: not shared across instances, reset on restart, pruned once the
|
|
72
|
+
window elapses. For distributed limits, enforce them in a shared store at the edge.
|
|
73
|
+
- `options.message` customizes only the 429 body; the status code is fixed at 429.
|
|
74
|
+
- These helpers only throw `HTTPResult`; they do not send responses themselves — they rely on the
|
|
75
|
+
API interface's handling of thrown `HTTPResult` values.
|
|
76
|
+
|
|
77
|
+
## Deeper reference
|
|
78
|
+
|
|
79
|
+
See this package's `docs/1.introduction.md` (Interface API Util Documentation: `assert`,
|
|
80
|
+
`assertValidation`, `RateLimit` sections) and the shipped `dist/*.d.ts` typings. Do not duplicate
|
|
81
|
+
them here.
|