V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
sofukwird

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

  •  
  •   sofukwird · Oct 7, 2023 · 1681 views
    This topic created in 933 days ago, the information mentioned may be changed or developed.

    缘起

    有些时候需要写一些简单的 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/[email protected]/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 气晕过去了

    • 配置环境太难了.
    • 需要包管理器, Deno 不需要
    • 编辑器支持不如 typescript
    fd9xr
        1
    fd9xr  
       Oct 7, 2023 via iPhone
    你在说什么东西……
    lscho
        2
    lscho  
       Oct 7, 2023
    你在说什么东西……
    sofukwird
        3
    sofukwird  
    OP
       Oct 7, 2023 via Android
    @fd9xr 确实,我这说的什么鬼呀,下沉了
    是一个支持热重载 typescript 路由
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3591 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 11:46 · PVG 19:46 · LAX 04:46 · JFK 07:46
    ♥ Do have faith in what you're doing.