up
date
‣
vip
slug
post0624194036
type
Post
CreatedTime
Jun 24, 2024 11:40 AM
status
Published
tags
Code
summary
在 Cloudflare Workers 部署一个 JSON as a Storage 服务
Link
category
Notion
password
IP
Email
cloudflare workers应用系列之4:Json database
cloudflare workers应用系列之4:Json database
在 Cloudflare Workers 部署一个 JSON as a Storage 服务
1 新建一个kv空间,随便名字, 为了以后区分可以取名为 JSONBASE,
2 新建一个workers,把代码换成以下的代码.
Code
const APIKEY = "xxxxxx"; /** * Cloudflare Workers 入口 */ addEventListener("fetch", (event) => { const { request } = event const headers = request.headers const authorization = headers.get("Authorization") // 检查 API 密钥 if (!authorization || authorization !== `Bearer ${APIKEY}`) { return fetch("https://http.cat/401") } if (request.method === "POST") { // 如果是 POST 请求,则写入 JSON 数据 return event.respondWith(WriteJSON(request)) } else if (request.method === "GET") { // 如果是 GET 请求,则读取 JSON 数据 return event.respondWith(ReadJSON(request)) } else { // 如果不是 GET 和 POST 请求,则返回 500 return fetch("https://http.cat/500"); } }); /** * * @param {*} response 解析 JSON 数据 * @returns */ async function gatherResponse(response) { const { headers } = response const contentType = headers.get("content-type") || "" if (contentType.includes("application/json")) { return JSON.stringify(await response.json()) } } /** * * @param {*} request 请求体 * @returns */ async function ReadJSON(request) { const { pathname } = new URL(request.url); // 从 KV 数据库中读取 JSON 数据 // 此步骤需要在 Cloudflare Workers 中绑定 KV 数据库并设置别名为 JSONBASE const value = await JSONBASE.get(pathname) if (value === null) { // 如果没有找到 JSON 数据,则返回 404 return fetch("https://http.cat/404"); } return new Response(value) } /** * * @param {*} request 请求体 * @returns */ async function WriteJSON(request) { const { pathname } = new URL(request.url); const Body = await gatherResponse(request) // 将 JSON 数据写入 KV 数据库 await JSONBASE.put(pathname, Body) return new Response(JSON.stringify({ Body }), { headers: { "Content-Type": "application/json" }, }); }
3 把kv空间绑定到这个workers上. 设置 变量 JSONBASE , KV命名空间绑定
4 可选,设置,触发器, 自定义域名. 绑定一个域名,国内可用, 不绑定的话国内不可用.
Workers 好就好在一次部署,终生不用再管,所以特别适合这种服务。
部署之后,就可以get和post了.
然后在kv空间就可以看到.