feat(rate-limit): carry the error brand instead of extending core
The original extended core's HttpError, which is a value import and makes the published plugin need core at run time. The brand is a registry-wide symbol, so core renders the 429 without this package depending on it, and it survives two copies of core in one tree where instanceof would not. The fields asserted here are exactly the ones HttpErrorLike declares. That core really renders them is proven end to end in the limiter's own tests, which read a 429 and its Retry-After back out of app.fetch. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+49
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { strict as assert } from 'node:assert';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { TooManyRequests } from '../src/errors.ts';
|
||||
import { MemoryStore } from '../src/memory-store.ts';
|
||||
|
||||
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
@@ -66,3 +67,18 @@ test('close is idempotent, because close() is called more than once in real apps
|
||||
|
||||
assert.doesNotThrow(() => store.close());
|
||||
});
|
||||
|
||||
// Convention rule 8, checked where it bites. The class never extends core's HttpError — it carries a
|
||||
// registry-wide symbol, which is what lets a plugin throw a 429 that core renders without importing
|
||||
// core, and what keeps working when two copies of core are in one tree (`instanceof` does not).
|
||||
test('carries the brand core recognises, and the fields core reads off it', () => {
|
||||
const error = new TooManyRequests('slow down', 30);
|
||||
|
||||
assert.equal((error as unknown as Record<symbol, unknown>)[Symbol.for('green-tea.http-error')], true);
|
||||
assert.equal(error.status, 429);
|
||||
assert.equal(error.message, 'slow down');
|
||||
assert.equal(error.headers['retry-after'], '30');
|
||||
assert.deepEqual(error.body, { message: 'slow down', status: 429 });
|
||||
// Still an Error: a throw that is not one loses the stack, and core rethrows before rendering.
|
||||
assert.ok(error instanceof Error);
|
||||
});
|
||||
Reference in new issue
Block a user