教程 koa tutorial

Todo API 服务

Todo API 服务是一个简单的待办事项管理系统,它允许用户创建、更新、删除和查看待办事项。通过 Koa 框架,我们可以快速构建一个支持这些基本操作的 API 服务。

1. 项目初始化与依赖安装

首先,初始化一个新的 Koa 项目,并安装必需的依赖:

bash
mkdir koa-todo-api
cd koa-todo-api
npm init -y
npm install koa koa-router koa-bodyparser

`

2. 基本服务器设置

创建一个 index.js 文件来启动我们的 Koa 应用并设置基本的路由。

javascript
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
const router = new Router();

app.use(bodyParser());

router.get('/', async (ctx) => {
  ctx.body = 'Todo API Service is running';
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

3. 创建 Todo 项目模型

为了存储待办事项,可以使用一个简单的内存数据存储(模拟数据库)。在实际应用中,您可以使用数据库(如 MySQL 或 MongoDB)。

javascript
let todos = [
  { id: 1, task: 'Learn Koa', completed: false },
  { id: 2, task: 'Build Todo API', completed: false },
];

4. 创建 Todo 接口

4.1 创建任务

通过 POST 请求创建新的 Todo 项目。客户端需提供 task 字段来描述待办事项内容。

javascript
router.post('/todos', async (ctx) => {
  const { task } = ctx.request.body;
  if (!task) {
    ctx.status = 400;
    ctx.body = { message: 'Task is required' };
    return;
  }
  const newTodo = {
    id: todos.length + 1,
    task,
    completed: false,
  };
  todos.push(newTodo);
  ctx.status = 201;
  ctx.body = newTodo;
});

4.2 获取所有任务

通过 GET 请求获取所有待办事项。

javascript
router.get('/todos', async (ctx) => {
  ctx.body = todos;
});

4.3 获取单个任务

通过 GET 请求根据任务 ID 获取单个待办事项。

javascript
router.get('/todos/:id', async (ctx) => {
  const todo = todos.find(t => t.id === parseInt(ctx.params.id));
  if (!todo) {
    ctx.status = 404;
    ctx.body = { message: 'Todo not found' };
    return;
  }
  ctx.body = todo;
});

4.4 更新任务

通过 PUT 请求更新一个任务的内容或完成状态。

javascript
router.put('/todos/:id', async (ctx) => {
  const todo = todos.find(t => t.id === parseInt(ctx.params.id));
  if (!todo) {
    ctx.status = 404;
    ctx.body = { message: 'Todo not found' };
    return;
  }
  const { task, completed } = ctx.request.body;
  if (task) todo.task = task;
  if (typeof completed === 'boolean') todo.completed = completed;
  ctx.body = todo;
});

4.5 删除任务

通过 DELETE 请求删除一个待办事项。

javascript
router.delete('/todos/:id', async (ctx) => {
  const index = todos.findIndex(t => t.id === parseInt(ctx.params.id));
  if (index === -1) {
    ctx.status = 404;
    ctx.body = { message: 'Todo not found' };
    return;
  }
  todos.splice(index, 1);
  ctx.status = 204;
});

5. 启动服务器

将上述所有代码整合到 index.js 文件中,然后启动服务器:

bash
node index.js

现在,您可以通过以下 API 路径来操作 Todo 项目:

  • POST /todos: 创建一个新任务。
  • GET /todos: 获取所有任务。
  • GET /todos/:id: 获取单个任务。
  • PUT /todos/:id: 更新任务。
  • DELETE /todos/:id: 删除任务。

6. 总结

通过 Koa 构建 Todo API 服务的过程展示了如何使用 Koa 中间件和路由来实现基础的 CRUD 操作。该 API 服务支持任务的增、删、查、改功能,适合用作学习和开发的小型项目。您可以根据需求扩展更多功能,如用户认证、数据存储改为数据库等。