Laravel  code tương tác với cloudfare Workers KV

Laravel code tương tác với cloudfare Workers KV

Workers KV là một kho lưu trữ dữ liệu cho phép bạn lưu trữ và truy xuất dữ liệu trên toàn cầu. Với Workers KV, bạn có thể xây dựng các API và trang web năng động và hiệu suất cao, hỗ trợ khối lượng đọc cao với độ trễ thấp.

Dưới đây là đoạn service giúp mọi người tương tác với Worrkers KV nhằm mục đích

  • Lưu trữ phản hồi API.
  • Lưu trữ cấu hình/sở thích của người dùng.
  • Lưu trữ thông tin xác thực người dùng.

Bạn cũng có thể xử dụng nó như 1 cache service 

<?php

namespace App\Services\Cloudflare;

use Illuminate\Support\Facades\Http;

class KVService
{
    protected $accountId;
    protected $namespaceId;
    protected $apiToken;

    public function __construct()
    {
        $this->accountId = env('CLOUDFLARE_ACCOUNT_ID');
        $this->namespaceId = env('CLOUDFLARE_NAMESPACE_ID');
        $this->apiToken = env('CLOUDFLARE_API_TOKEN');
    }

    // Lưu dữ liệu vào KV
    public function put($key, $value)
    {
        $url = "https://api.cloudflare.com/client/v4/accounts/{$this->accountId}/storage/kv/namespaces/{$this->namespaceId}/values/{$key}";

        return Http::withToken($this->apiToken)
            ->put($url, $value)
            ->successful();
    }

    // Lấy dữ liệu từ KV
    public function get($key)
    {
        $url = "https://api.cloudflare.com/client/v4/accounts/{$this->accountId}/storage/kv/namespaces/{$this->namespaceId}/values/{$key}";
        $response = Http::withToken($this->apiToken)->get($url);
        return $response->successful() ? $response->body() : null;
    }

    // Xóa dữ liệu khỏi KV
    public function delete($key)
    {
        $url = "https://api.cloudflare.com/client/v4/accounts/{$this->accountId}/storage/kv/namespaces/{$this->namespaceId}/values/{$key}";
        return Http::withToken($this->apiToken)->delete($url)->successful();
    }
    // Lấy danh sách tất cả các key
    public function listKeys($limit = 1000)
    {
        $url = "https://api.cloudflare.com/client/v4/accounts/{$this->accountId}/storage/kv/namespaces/{$this->namespaceId}/keys?limit={$limit}";
        $response = Http::withToken($this->apiToken)->get($url);
        if (!$response->successful()) {
            return [];
        }
        return $response->json()['result'] ?? [];
    }
    // Lấy tất cả key-value trong KV
    public function getAll()
    {
        $keys = $this->listKeys();
        $data = [];
        foreach ($keys as $key) {
            $keyName = $key['name'];
            $value = $this->get($keyName);
            if ($value !== null) {
                $data[$keyName] = $value;
            }
        }
        return $data;
    }
}