cloudflare workers应用系列之3:博客点赞功能
发表于:2024-05-01 更新于5/31/2024, 1:41:19 AM
emaction.frontend
emaction • Updated May 11, 2024
cloudflare workers应用系列之3: 博客点赞功能 workers应用之: 博客点赞功能
emaction 是一个标准 web component,可以用在任何页面中。
后台在cloudflare中搭建, 前台一个js文件搞定
只需两行代码,即可为页面添加 emoji reaction 功能。
通过 CDN 引入(推荐) 然后在相应的post页面中放入下面代码就OK了
进阶使用: reactTargetId 指定相应的id, 可以用post.id, 或post.slug或直接用post.title.这样从后台可以直观查看点赞结果. 增加”reactTargetId”参数 并且可以在列表页和详情页共用一个结果. endpoint指定自己搭建的后台
这是后台的结果_________ 💡
测试
id
target_id
reaction_name
count
created_at
updated_at
1
围城之外
thumbs-up
1
14
1
自己搭建一个免费后端: 新建一个D1数据库 名字起个容易区分的,可以人工创建表, 也可以命令行创建表 新建一个workers
代码如下, 替换原来的代码后, 进行部署. 绑定域名,绑定数据库,绑定域名. 在该workers的设置- 触发器里,绑定一个域名,因为默认的被墙了. 在该workers的设置- 变量里, 进行D1数据库绑定. 再返回编辑代码, 再点开域名,https://api-emaction.xxxxx.workers.dev/ 后是一张404的照片, 就表示成功了.
测试:::::::::::: cloudflare workers应用系列之3: 博客点赞功能
emaction 是一个标准 web component,可以用在任何 html 页面中。只需两行代码,即可为页面添加 emoji reaction 功能。
<script type="module" src="https://cdn.jsdelivr.net/gh/emaction/frontend.dist@1.0.11/bundle.js"></script>
<emoji-reaction></emoji-reaction>
<emoji-reaction
availableArrayString="
👍,thumbs-up;
😄,smile-face;
🎉,party-popper;
😕,confused-face;
❤️,red-heart;
🚀,rocket;
👀,eyes;"
reactTargetId={post.title}
endpoint="https://up.51xmi.com"
></emoji-reaction>
CREATE TABLE reactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
target_id TEXT NOT NULL,
reaction_name TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
// src/worker.js
var cors_headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PATCH"
};
var worker_default = {
// eslint-disable-next-line no-unused-vars
async fetch(request, env, ctx) {
const url = new URL(request.url);
const { searchParams } = url;
if (request.method.toLowerCase() === "get" && url.pathname === "/reactions") {
const targetId = searchParams.get("targetId");
if (!targetId) {
return new Response("Empty targetId", {
status: 400,
headers: {
...cors_headers
}
});
}
const result = await env.d1.prepare("select reaction_name, count from reactions where target_id = ?1;").bind(targetId).all();
if (result?.success && result.results) {
return this.returnJson(0, "success", { reactionsGot: result.results });
} else {
return this.returnJson(1, "fail");
}
} else if (request.method.toLowerCase() === "patch" && url.pathname === "/reaction") {
const targetId = searchParams.get("targetId");
const reaction_name = searchParams.get("reaction_name");
let diff = parseInt(searchParams.get("diff"));
if (typeof diff === "number" && isFinite(diff)) {
diff = diff > 0 ? 1 : -1;
} else {
diff = 0;
}
if (!targetId || !reaction_name || !diff) {
return new Response("Invalid Response.", {
status: 400,
headers: { ...cors_headers }
});
}
const count = await env.d1.prepare("select count from reactions where target_id = ?1 and reaction_name = ?2").bind(targetId, reaction_name).first("count");
let stmt = null;
if (count == null) {
stmt = env.d1.prepare(`insert into reactions (target_id, reaction_name, count, created_at, updated_at) values (?1, ?2, ?3, ${Date.now()}, ${Date.now()})`).bind(targetId, reaction_name, Math.max(0, diff));
} else {
stmt = env.d1.prepare(`update reactions set count = ?1, updated_at = ${Date.now()} where target_id = ?2 and reaction_name = ?3`).bind(Math.max(0, count + diff), targetId, reaction_name);
}
const result = await stmt.run();
return this.returnJson(result.success ? 0 : 1, result.success ? "success" : "fail");
}
if (request.method.toLowerCase() === "options") {
return new Response(
`<img src="https://http.cat/200" alt="That's Ok.">`,
{
status: 200,
headers: {
"Content-Type": "text/html",
...cors_headers
}
}
);
}
return new Response(
`<img src="https://http.cat/404" alt="404 Not Found">`,
{
status: 404,
headers: {
"Content-Type": "text/html",
...cors_headers
}
}
);
},
returnJson(code, msg, data) {
return new Response(JSON.stringify({
code,
msg,
data
}), {
headers: {
"content-type": "application/json;charset=UTF-8",
...cors_headers
}
});
}
};
export {
worker_default as default
};
//# sourceMappingURL=worker.js.map