为你的网站添加 Do you like me 小组件

3 min read

应该有人注意到博主在侧边栏添加了一个 Do You Like Me 的小组件,其实我觉得更为简便的方法就是使用 PHP+SQL+AJAX ,但本着折腾+降低成本(白嫖)的想法,用 VercelLeandCloudNode.JS 撸了一个出来。

Node版本

由于 Node.Js 属于半入门状态,所以代码质量不高,但程序终究是以奇怪的方式跑起来了。

项目地址:https://github.com/5ime/likeMe

PHP 版本

由于我是 vercel 托管没有 创建修改 文件的权限,所以说每一次获取 like 数量都会请求 LeanCloud ,导致请求数很高。

所以又撸了一个 PHP 版本出来,把 like 数量写入到了 count.dat 文件中,请求时读取 count.dat 点击后更新 count.dat。下面的代码上传到自己的服务器即可。

先使用 composer 安装LeanCloud SDK:

composer require leancloud/leancloud-sdk

具体代码如下,参数获取组件调用 请参考 https://github.com/5ime/likeMe/

<?php
// title: Do U Like Me
// update: 2024-05-03
// author: iami233
error_reporting(0);
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

require_once("vendor/autoload.php");
use LeanCloud\Query;
use LeanCloud\Client;
use LeanCloud\CloudException;

// 初始化LeanCloud客户端一次,避免每次请求都初始化
initializeLeanCloud();

// 文件名常量
define("COUNT_FILE", "count.dat");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $response = incrementLikeCount();
} else {
    $response = getLikeCount();
}

echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

function initializeLeanCloud() {
    // 参数依次为 app-id, app-key, master-key
    Client::initialize("你的app-id", "你的app-key", "你的master-key");
    // Client::setDebug(true); // 可以开启调试模式查看详细信息
}

function incrementLikeCount() {
    $query = new Query("likeCount");
    $objectId = "你的objectId"; // 修改为你的objectId
    try {
        $todo = $query->get($objectId);
        $todo->increment("count", 1);
        $todo->save();
        $count = $todo->get("count");
        writeToFile($count);
        return [
            'code' => 200,
            'msg' => 'success'
        ];
    } catch (CloudException $e) {
        return [
            'code' => 500,
            'msg' => $e->getMessage()
        ];
    }
}

function getLikeCount() {
    $count = readFromFile();
    return [
        'code' => 200,
        'msg' => 'success',
        'data' => [
            'count' => $count
        ]
    ];
}

function writeToFile($data) {
    if ($file = fopen(COUNT_FILE, "w")) {
        fwrite($file, $data);
        fclose($file);
    }
}

function readFromFile() {
    if ($file = fopen(COUNT_FILE, "r")) {
        $count = fread($file, filesize(COUNT_FILE));
        fclose($file);
        return $count;
    }
    return "0";
}
?>