经测试,当前实例下所有url请求都能被拦截器捕获到。
那就可以把url中的path通过转换,匹配到相应的云函数。
只要能异步加载云函数,那也算是变相的解决了这个问题了。

废话不多说,上代码。

// 测试函数1,命名为 hello_world
export default {
    data: 'hello world'
}
// 测试函数2,命名为 test_path
export default async function (ctx: FunctionContext) {
    return { data: 'test path api' }
}
// 最后是我们的拦截器 __interceptor__
export async function main(ctx: FunctionContext) {
    // 这里,简单的把拿到的url转换成云函数的格式 /aaa/bbb -> /aaa_bbb
    // 当然,还可以适配/id/[id] 或者/news/detail-[id] 自行完善这里即可。
    const funcName = ctx.request.path.replace(
        /(^\/)|(\/)/g,
        (match, p1, p2) => {
            if (p1) {
                return p1
            } else {
                return '_'
            }
        }
    )
    try {
        // 尝试异步导入云函数
        const res = await require(`@${funcName}`)
        // 由于两个例子中一个返回的json,一个返回的function,所以这里做了一层判断
        if (res.default && typeof res.default === 'function') {
            const instance = await res.default()
            ctx.response.send(instance)
        } else {
            ctx.response.send(res.default)
        }
    } catch (err) {
        // 这里是没找到云函数时的处理事件,通常可以返回400错误或者403错误,当然也可以渲染个404页面。
        ctx.response.send({
            err: err.message,
            path: ctx.request.path,
            funcName,
            query: ctx.query,
            body: ctx.body
        })
    }
    return false
}

最后,我们直接访问 xxx.laf.run/hello/world 或者xxx.laf.run/test/path 即可。

update:20230706
已发布到函数市场:https://laf.run/market/templates/649ccfd29622c81462953d70

1 个月 后