# 使用 Deno Deploy 部署一个随机图片文字服务

> [使用 Deno Deploy 部署一个随机图片文字服务](https://www.ftls.xyz/posts/2024-01-09-deno-deploy-random-images-text-service/)
> Penned by [恐咖兵糖](https://www.ftls.xyz/) on 2024-01-09


使用 Deno Deploy 部署一个随机图片文字服务。

<!--more-->

## Deno 介绍

> Deno Deploy 是一个全球分布式的无服务器 JavaScript 应用平台。您的 JavaScript、TypeScript 和 WebAssembly 代码在靠近用户地理位置的托管服务器上运行，实现低延迟和更快的响应时间。部署的应用程序在快速轻量级的 V8 隔离上运行，而不是虚拟机，由 Deno 运行时提供支持。 
![](https://cdn.ftls.xyz/images/2024/01/202401091852101.png)
中文文档 https://docs.denohub.com/deno/deploy/manual

Deno Deploy 可使用 KV ，Cron 内置服务，自带分析，日志，Github 自动集成部署。支持 Fresh ，SvelteKit ，Nuxt，Next.js 等等模板。有一定免费额度。（每月 1M 次请求，100GB 流量等限制）

**Deno Deploy 可选模板**

![](https://cdn.ftls.xyz/images/2024/01/202401091907057.png)

![](https://cdn.ftls.xyz/images/2024/01/202401091907154.png)

## 概述

项目地址 https://github.com/kkbt0/deno-demo1
效果 https://healthy-tiger-40.deno.dev/

## 步骤

使用起来很简单，项目上传到 Github 

1. Deno 在本地跑通后，上传项目到 Github。如 https://github.com/kkbt0/deno-demo1
2. 登录 https://dash.deno.com/
3. 选择项目进行授权，安装 app https://github.com/apps/deno-deploy
4. 部署完成，查看效果
5. 后续上传到 Github 的代码，会自动部署到 Deno Deploy


## 效果

![](https://cdn.ftls.xyz/images/2024/01/202401091900763.png)

![](https://cdn.ftls.xyz/images/2024/01/202401091901257.png)

同时贴出代码。和 https://github.com/kkbt0/deno-demo1 一致

## 代码

1. 程序入口

server.ts  
```ts
function getRandomJsonItem(filePath: string): string {
  const jsonData = JSON.parse(Deno.readTextFileSync(filePath));
  const randomItem = jsonData[Math.floor(Math.random() * jsonData.length)];
  return randomItem;
}

function addOne(value: any): number {
  if (isNaN(value)) {
    value = 0;
  }
  return Number(value) + 1;
}

async function setKeyValue(path: string): Promise<number> {
  const kv = await Deno.openKv();
  const num = await kv.get(["demo1", path]);
  const newNum = addOne(num.value);
  await kv.set(["demo1", path], newNum);
  console.log("Path:", path, "Num:", newNum);
  return newNum;
}

async function getKeyValue(): Promise<string> {
  const kv = await Deno.openKv();
  const num1 = await kv.get(["demo1", "/"]);
  const num2 = await kv.get(["demo1", "/gushi"]);
  const num3 = await kv.get(["demo1", "/images"]);
  return `<div> / ${num1.value}<br> /gushi ${num2.value}<br> /images ${num3.value}</div>`;
}

const handler = async (request: Request): Promise<Response> => {
  const url = new URL(request.url);
  setKeyValue(url.pathname);
  switch (url.pathname) {
    case "/":
      const num = await getKeyValue();
      return new Response(
        Deno.readTextFileSync("index.html").replace(/{{num}}/g, num),
        { status: 200, headers: { "Content-Type": "text/html" } }
      );
    case "/gushi":
      return new Response(getRandomJsonItem("古诗.json"), { status: 200 });
    case "/images":
      return new Response("302", {
        status: 302,
        headers: { Location: getRandomJsonItem("images.json") },
      });
    default:
      return new Response("404", { status: 404 });
  }
};

console.log(`HTTP server running. Access it at: http://localhost:1024/`);
Deno.serve({ port: 1024, hostname: "0.0.0.0", handler });
```
2. 主页

index.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Deno Demo</title>
</head>
<body>
    <h1>Deno Demo</h1>
    <div><a href="https://www.ftls.xyz/posts/2024-01-09-deno-deploy-random-images-text-service/">教程</a></div>
    <p>随机 图片 古诗以下链接：</p>
    <ul>
        <li><a href="/images" target="_blank">随机图片</a></li>
        <li><a href="/gushi" target="_blank">随机古诗</a></li>
    </ul>
    <div>统计 {{num}}</div>
</body>
</html>
```

3. 数据文件

images.json
```json
[
    "https://img.zcool.cn/community/0176b05e254499a801216518ff2bf4.jpg?x-oss-process=image/auto-orient,1/resize,m_lfit,w_1280,limit_1/sharpen,100",
    "https://n.sinaimg.cn/sinacn10101/492/w1080h1812/20190319/ae63-hukwxnv3750034.jpg",
    "https://s2.ciyuanjie.cn/uploads/2020/04/323075.jpg",
    "https://pic4.zhimg.com/v2-d81f45bcbda578ba89e3ebcfa90baa87_r.jpg"
]
```
古诗.json
```json
[
    "愿得一心人，白头不相离",
    "十年生死两茫茫，不思量，自难忘。",
    "迟日江山丽，春风花草香。",
    "连雨不知春去，一晴方觉夏深。",
    "荷叶罗裙一色裁，芙蓉向脸两边开。"
]
```

4. justfile

```
run:
    deno run --allow-net --allow-read  --unstable server.ts
```
