Add ETag to WebAPI for caching of unchanged resources (#17)

This commit is contained in:
Colette Contreras
2020-09-18 05:30:29 +08:00
committed by GitHub
parent 795e9c0ffc
commit 4ea3e8f140
2 changed files with 17 additions and 1 deletions

View File

@@ -318,4 +318,17 @@ class Helpers
return $log->save();
}
public static function abortIfNotModified($data): string {
$req = request();
// Only for "GET" method
if (!$req->isMethod('GET')) {
return "";
}
$etag = sha1(json_encode($data));
if ($etag == $req->header("IF-NONE-MATCH")) {
abort(304);
}
return $etag;
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\WebApi;
use App\Components\Helpers;
use App\Models\Node;
use App\Models\NodeHeartBeat;
use App\Models\NodeOnlineLog;
@@ -53,6 +54,8 @@ class BaseController
$data = [],
$addition = []
): JsonResponse {
$etag = Helpers::abortIfNotModified($data);
$data = [
'status' => $status,
'code' => $code,
@@ -64,7 +67,7 @@ class BaseController
$data = array_merge($data, $addition);
}
return Response::json($data);
return Response::json($data)->header('ETAG', $etag);
}
// 上报节点在线人数