miniflare
Version:
Fun, full-featured, fully-local simulator for Cloudflare Workers
49 lines (48 loc) • 1.64 kB
JavaScript
// src/workers/ratelimit/ratelimit.worker.ts
var RatelimitOptionKeys = ["key", "limit", "period"], RatelimitPeriodValues = [10, 60];
function validate(test, message) {
if (!test)
throw new Error(message);
}
var Ratelimit = class {
fetcher;
limitVal;
period;
constructor(config) {
this.fetcher = config.fetcher, this.limitVal = config.limit, this.period = config.period;
}
// method that counts and checks against the limit, delegating the actual
// bucket/epoch bookkeeping to the `RateLimiterObject` Durable Object
async limit(options) {
validate(
typeof options == "object" && options !== null,
"invalid rate limit options"
);
let invalidProps = Object.keys(options ?? {}).filter(
(key2) => !RatelimitOptionKeys.includes(key2)
);
validate(
invalidProps.length == 0,
`bad rate limit options: [${invalidProps.join(",")}]`
);
let {
key = "",
limit = this.limitVal,
period = this.period
} = options;
return validate(typeof key == "string", `invalid key: ${key}`), validate(typeof limit == "number", `limit must be a number: ${limit}`), validate(typeof period == "number", `period must be a number: ${period}`), validate(
RatelimitPeriodValues.includes(period),
`unsupported period: ${period}`
), await (await this.fetcher.fetch("http://ratelimit/limit", {
method: "POST",
body: JSON.stringify({ key, limit, period })
})).json();
}
};
function ratelimit_worker_default(env) {
return new Ratelimit(env);
}
export {
ratelimit_worker_default as default
};
//# sourceMappingURL=ratelimit.worker.js.map