> For the complete documentation index, see [llms.txt](https://zg-zhang.gitbook.io/note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zg-zhang.gitbook.io/note/deno/3-0/3-1.md).

# Deno 小小实战 Rest Todo API

> GitHub <https://github.com/zg-zhang/Deno-Todo>

之前拿 Node.js 做 Web 应用开发，我们可以选择 Express、Koa 等框架

同理，在 Deno 中也可以使用 deno-express、Oak 等框架，这次使用 Oak 现在这个在 github 上拥有最多 star 的框架

## Oak 简介

> A middleware framework for Deno's http server, including a router middleware. This middleware framework is inspired by Koa and middleware router inspired by Koa-router

Oak 是一个包含路由的 http 框架，它的灵感来自于 Koa 和 Koa-router

实例：

```typescript
import { Application } from 'https://deno.land/x/oak/mod.ts';

const app = new Application();

app.use(ctx => {
    ctx.response.body = "hello Deno!"
})

await app.listen({ port: 8080 });
```

多个中间件的实例：

```typescript
import { Application } from 'https://deno.land/x/oak/mod.ts';

const app = new Application();

// Logger 
app.use(async (ctx, next) => {
    await next();
    const rt = ctx.response.headers.get("X-Response-Time");
    console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`)
})

// Timing
app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.response.headers.set("X-Response-Time", `${ms}ms`);
})

// Hello World
app.use(ctx => {
    ctx.response.body = "Hello World"
})

await app.listen({ port: 8080 })
```

## Oak 实战

### 需求分析

* 添加新的 Todo
* 显示 Todo 列表
* 获取指定 Todo 的详情
* 移除指定 Todo
* 更新指定 Todo

### 初始化项目结构

├─ db 作为本地数据库，存放 Todo 数据 ├─ handlers 存放路由处理器 ├─ middlewares 存放中间件，用于处理每个请求 ├─ models 存放模型定义，在我们的示例中只包含 Todo 接口 ├─ services 存放服务层程序 ├─ config.ts 包含应用的全局配置信息 ├─ index.ts 应用的入口文件 └─ routing.ts 包含 API 路由信息
