nestjs-阿里云云函数部署

9次阅读

共计 1663 个字符,预计需要花费 5 分钟才能阅读完成。

之前就想让 nest.js 在阿里云上部署 serverless 试试,但在网上没有搜到相关的例子

只找到了 express 的例子,但我不知道怎么从 nest.js 获得 express app 对象。就此陷入僵局,但在搜索的过程中发现腾讯云是有 nest.js 的例子的,一看他们的代码,(•̀ ω •́)✧ express app 原来是这么拿的啊, 只要用 ExpressAdapter 就好了,但之前没用过就不了解

然后我刷刷刷的写出了如下代码

//file://src/index.ts
import {NestFactory} from "@nestjs/core";
import {ExpressAdapter} from "@nestjs/platform-express";
import {Server} from "@webserverless/fc-express";
import express from "express";
import {AppModule} from "./app.module";
let p = (async () => {const adapter = new ExpressAdapter(app);
 const app2 = await NestFactory.create(AppModule, adapter);
  app2.enableCors();
 await app2.init();
 return new Server(app);
})();

module.exports.handler = function (req, res, context) {p.then((server) => {server.httpProxy(req, res, context);
  });
};

结果(;´д `)ゞ 他啪啪啪的一直超时,我就不明白了他为啥调用一直超时。

经过一行行的测试发现 `module.exports.handler` 中一旦是异步执行 `server.httpProxy(req, res, context)` 哪怕是这样写 `setTimeout(()=>{server.httpProxy(req, res, context)},1)` 他也会超时。这里不知道原因,也不想浪费时间

既然找到了症结那就简单了,咻咻咻一段修改得到如下代码

//file://src/index.ts
import {NestFactory} from "@nestjs/core";
import {ExpressAdapter} from "@nestjs/platform-express";
import {Server} from "@webserverless/fc-express";
import express from "express";
import {AppModule} from "./app.module";

const app = express();

let p = (async () => {const adapter = new ExpressAdapter(app);
 const app2 = await NestFactory.create(AppModule, adapter);
  app2.enableCors();
 await app2.init();})();
app.use(function (req, res, next) {console.log(`[time:${Date.now()} [url:${req.url}]]`);
  p.then(() => next());
});

const server = new Server(app);

module.exports.handler = function (req, res, context) {server.httpProxy(req, res, context);
};

完美运行,诀窍就是 `module.exports.handler` 内部不异步执行了,等待 nest.js 初始化的这个操作放到 express 中间件中去就行了

[样例代码 github 地址](https://github.com/2234839/nest.js_aliyun_serverless)

正文完
 0