API 调节器
Flarum comes with a builtin Flarum\Api\Middleware\ThrottleApi middleware for throttling requests to the API.
这将运行在每一个 API 路由上,扩展可以将自己的自定义逻辑添加到节流请求中。
Some forum routes (login, register, forgot password, etc) work by calling an API route under the surface. The ThrottleApi middleware does not currently run for these requests, but that is planned for the future.
The ThrottleApi middleware does not currently run for these requests, but that is planned for the future.
自定义限流处理器
自定义限流处理器格式非常简单:您需要的只是一个关闭或可调用的类,将当前请求作为一个参数, 并返回一个:
false: This explicitly bypasses throttling for this request, overriding all other throttlerstrue: This marks the request as to be throttled.null: This means that this throttler doesn't apply. Any other outputs will be ignored, with the same effect asnull.
Throttlers will be run on EVERY request, and are responsible for figuring out whether or not they apply. For example, consider Flarum's post throttler: 例如, 请查看 Flarum 的 post 限流器:
use DateTime;
use Flarum\Http\RequestUtil;
use Flarum\Post\Post;
function ($request) {
if (! in_array($request->getAttribute('routeName'), ['discussions.create', 'posts.create'])) {
return;
}
$actor = RequestUtil::getActor($request);
if ($actor->can('postWithoutThrottle')) {
return false;
}
if (Post::where('user_id', $actor->id)->where('created_at', '>=', new DateTime('-10 seconds'))->exists()) {
return true;
}
};
Throttlers can be added or removed via the ThrottleApi middleware in extend.php. For example:
<?php
use Flarum\Extend;
return [
// Other extenders
(new Extend\ThrottleApi())
->set('throttleAll', function () {
return false;
})
->remove('bypassThrottlingAttribute'),
// Other extenders
];