采用 PHP 模式的 Deno, 用 TypeScript 快速编写简单接口

215 天前
 sofukwird

缘起

有些时候需要写一些简单的 api 接口, 简单到可以部署到 serverless 平台上的那种

但没有一个 serverless 有很好的体验于是就写了这个, 可以自己部署的 typescript serverless function

serverless 的尽头就是 PHP, 所以我采用了和 PHP 一样的文件路由, 但略有不同

fetch("http://localhost:8000/foo/bar");
// 会依次尝试以下路径
[
  "/foo/bar/+index.ts",
  "/foo/bar/[rest]/+index.ts",
  "/foo/[rest]/+index.ts",
  "/foo/bar/[...rest]/+index.ts",
  "/foo/[...rest]/+index.ts",
  "/[...rest]/+index.ts",
];

ps: +index.ts 这种文件名是受 sveltekit 启发的

如何使用

创建 uapi 根文件夹 ./example

deno run -A https://deno.land/x/uapi@v2.0.5/start.ts ./example

编辑 ./example/+index.ts.

// ./example/+index.ts
export default {
  fetch: () => new Response("hello uapi"),
};

测试是否正常访问.

curl http://localhost:8000/
# logout: hello uapi

ps: 编辑 ./example/+index.ts 保存后请求会得到最新的响应

其他

为什么不使用 PHP

因为我一开始学编程的时候就被 PHP 气晕过去了

679 次点击
所在节点    JavaScript
3 条回复
fd9xr
215 天前
你在说什么东西……
lscho
215 天前
你在说什么东西……
sofukwird
215 天前
@fd9xr 确实,我这说的什么鬼呀,下沉了
是一个支持热重载 typescript 路由

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/979412

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX