worktopCloudflare Workers 的下一代 Web 框架

联合创作 · 2023-09-20 01:40

worktop 是面向 Cloudflare Workers 的下一代 Web 框架。

特性:

  • 轻量级
  • 一流的 TypeScript 支持
  • 自定义中间件支持
  • 用于点菜功能的组织良好的子模块*
  • 包括支持模式定义的路由器
  • 熟悉的请求-响应处理程序 API
  • 支持async/await处理程序
  • 完全 treeshakable
import { Router } from 'worktop';
import * as Cache from 'worktop/cache';
import { uid as toUID } from 'worktop/utils';
import { read, write } from 'worktop/kv';
import type { KV } from 'worktop/kv';

declare var DATA: KV.Namespace;

interface Message {
  id: string;
  text: string;
  // ...
}

// Initialize
const API = new Router();


API.add('GET', '/messages/:id', async (req, res) => {
  // Pre-parsed `req.params` object
  const key = `messages::${req.params.id}`;

  // Assumes JSON (can override)
  const message = await read<Message>(DATA, key);

  // Alter response headers directly
  res.setHeader('Cache-Control', 'public, max-age=60');

  // Smart `res.send()` helper
  // ~> automatically stringifies JSON objects
  // ~> auto-sets `Content-Type` & `Content-Length` headers
  res.send(200, message);
});


API.add('POST', '/messages', async (req, res) => {
  try {
    // Smart `req.body` helper
    // ~> parses JSON header as JSON
    // ~> parses form-like header as FormData, ...etc
    var input = await req.body<Message>();
  } catch (err) {
    return res.send(400, 'Error parsing request body');
  }

  if (!input || !input.text.trim()) {
    return res.send(422, { text: 'required' });
  }

  const value: Message = {
    id: toUID(16),
    text: input.text.trim(),
    // ...
  };

  // Assumes JSON (can override)
  const key = `messages::${value.id}`;
  const success = await write<Message>(DATA, key, value);
  //    ^ boolean

  // Alias for `event.waitUntil`
  // ~> queues background task (does NOT delay response)
  req.extend(
    fetch('https://.../logs', {
      method: 'POST',
      headers: { 'content-type': 'application/json '},
      body: JSON.stringify({ success, value })
    })
  );

  if (success) res.send(201, value);
  else res.send(500, 'Error creating record');
});


API.add('GET', '/alive', (req, res) => {
  res.end('OK'); // Node.js-like `res.end`
});


// Attach "fetch" event handler
// ~> use `Cache` for request-matching, when permitted
// ~> store Response in `Cache`, when permitted
Cache.listen(API.run);
浏览 4
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报