Laravel code tương tác với cloudfare D1 database

Laravel code tương tác với cloudfare D1 database

D1 là cơ sở dữ liệu không máy chủ được Cloudflare quản lý với ngữ nghĩa SQL của SQLite, chức năng phục hồi sau thảm họa tích hợp và quyền truy cập Worker và HTTP API.
D1 được thiết kế để mở rộng theo chiều ngang trên nhiều cơ sở dữ liệu nhỏ hơn (10 GB), chẳng hạn như cơ sở dữ liệu theo người dùng, theo người thuê hoặc theo thực thể. D1 cho phép bạn xây dựng các ứng dụng với hàng nghìn cơ sở dữ liệu mà không mất thêm chi phí để cô lập với nhiều cơ sở dữ liệu. Giá của D1 chỉ dựa trên chi phí truy vấn và lưu trữ.

Dưới đây là đoạn service giúp bạn tương tác với D1

client = new Client();
        $this->accountId = env('CLOUDFLARE_ACCOUNT_ID');
        $this->databaseId = env('CLOUDFLARE_DB_ID');
        $this->apiKey = env('CLOUDFLARE_API_GLOBAL_ID');
        $this->bearkey = env('CLOUDFLARE_API_TOKEN_ALL', '');
        $this->authEmail = '[email protected]'; // Có thể đưa vào env nếu cần
    }

    /**
     * Lấy tất cả dữ liệu từ bảng bất kỳ
     */
    public function getAll(string $table, string $orderBy = null, string $orderDirection = 'ASC')
    {
        try {
            $sql = "SELECT * FROM {$table}";

            if ($orderBy) {
                $sql .= " ORDER BY {$orderBy} {$orderDirection}";
            }

            return $this->executeQuery($sql);
        } catch (RequestException $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    /**
     * Truy vấn dữ liệu từ bảng bất kỳ với điều kiện động và hỗ trợ orderBy
     */
    public function queryTable(string $table, array $params = [], string $orderBy = null, string $orderDirection = 'DESC')
    {
        try {
            $whereClauses = [];
            $queryParams = [];

            foreach ($params as $key => $value) {
                $whereClauses[] = "$key = ?";
                $queryParams[] = $value;
            }

            $sql = "SELECT * FROM {$table}";
            if (!empty($whereClauses)) {
                $sql .= " WHERE " . implode(" AND ", $whereClauses);
            }

            if ($orderBy) {
                $sql .= " ORDER BY {$orderBy} {$orderDirection}";
            } else {
                $sql .= " ORDER BY id {$orderDirection}";
            }

            return $this->executeQuery($sql, $queryParams);
        } catch (RequestException $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    /**
     * Thêm bản ghi vào bảng bất kỳ
     */
    public function insertRecord(string $table, array $data)
    {
        try {
            $columns = implode(", ", array_keys($data));
            $placeholders = implode(", ", array_fill(0, count($data), "?"));
            $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";

            return $this->executeQuery($sql, array_values($data));
        } catch (RequestException $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    /**
     * Cập nhật bản ghi trong bảng bất kỳ
     */
    public function updateRecord(string $table, int $id, array $data)
    {
        try {
            $setClauses = [];
            $queryParams = [];

            foreach ($data as $key => $value) {
                $setClauses[] = "$key = ?";
                $queryParams[] = $value;
            }

            $sql = "UPDATE {$table} SET " . implode(", ", $setClauses) . " WHERE id = ?";
            $queryParams[] = $id;

            return $this->executeQuery($sql, $queryParams);
        } catch (RequestException $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    /**
     * Xóa bản ghi trong bảng bất kỳ
     */
    public function deleteRecord(string $table, int $id)
    {
        try {
            $sql = "DELETE FROM {$table} WHERE id = ?";
            return $this->executeQuery($sql, [$id]);
        } catch (RequestException $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    /**
     * Thực thi query đến Cloudflare D1
     */
    private function executeQuery(string $sql, array $params = [])
    {
        $response = $this->client->post("https://api.cloudflare.com/client/v4/accounts/{$this->accountId}/d1/database/{$this->databaseId}/query", [
            'headers' => array_merge([
                'Content-Type' => 'application/json',
            ], isset($this->bearkey) && $this->bearkey !== ''
                ? ['Authorization' => 'Bearer ' . $this->bearkey]
                : [
                    'X-Auth-Email' => $this->authEmail,
                    'X-Auth-Key' => $this->apiKey,
                ]
            ),
            'json' => [
                'sql' => $sql,
                'params' => $params,
            ],
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }
}