Skip to content

Commit 7f18f2c

Browse files
committed
fix: add sls initialize before creating server
1 parent 1b4f780 commit 7f18f2c

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed

README.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ TENCENT_SECRET_KEY=123
157157

158158
## 静态资源服务
159159

160-
如果想要支持 `express.static()` 返回静态资源,比如图片之类的,需要在入口文件 `sls.js` 中指定相关 `MIME` 类型的文件为二进制,这样云函数在返回请求结果给 API 网关是,会对指定类型进行 `Base64` 编码,最终返回给客户端才能正常显示。如下:
160+
如果想要支持返回静态资源,比如图片之类的,需要在入口文件 `sls.js` 中指定相关 `MIME` 类型的文件为二进制,这样云函数在返回请求结果给 API 网关是,会对指定类型进行 `Base64` 编码,最终返回给客户端才能正常显示。如下:
161161

162162
```js
163163
const express = require('express')
@@ -175,6 +175,32 @@ module.exports = app
175175

176176
更多文件类型的 `MIME` 类型,可参考 [mime-db](https://github.com/jshttp/mime-db/blob/master/db.json)
177177

178+
### slsInitialize 应用初始化
179+
180+
有些时候,Express 服务在启动前,需要进行一个初始化操作,比如数据库建连,就可以通过在 Express 实例对象上添加 `slsInitialize` 函数来实现,如下:
181+
182+
```js
183+
const express = require('express')
184+
const mysql = require('mysql2/promise')
185+
186+
const app = new express()
187+
188+
// ...
189+
190+
app.slsInitialize = async () => {
191+
app.db = await mysql.createConnection({
192+
host: 'localhost',
193+
user: 'root',
194+
database: 'test'
195+
})
196+
}
197+
198+
// don't forget to export!
199+
module.exports = app
200+
```
201+
202+
这样应用部署到云函数后,在函数服务逻辑执行前,会先执行 `slsInitialize()` 函数,来初始化数据库连接。
203+
178204
## License
179205

180206
MIT License

src/_shims/handler.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,18 @@ exports.handler = async (event, context) => {
2020
app.request.__SLS_EVENT__ = event
2121
app.request.__SLS_CONTEXT__ = context
2222

23+
// provide sls intialize hooks
24+
if (app.slsInitialize && typeof app.slsInitialize === 'function') {
25+
await app.slsInitialize()
26+
}
27+
2328
// cache server, not create repeatly
2429
if (!server) {
2530
server = createServer(app, null, app.binaryTypes || [])
2631
}
2732

2833
context.callbackWaitsForEmptyEventLoop = app.callbackWaitsForEmptyEventLoop === true
2934

30-
// provide sls intialize hooks
31-
if (app.slsInitialize && typeof app.slsInitialize === 'function') {
32-
await app.slsInitialize()
33-
}
34-
3535
const result = await proxy(server, event, context, 'PROMISE')
3636
return result.promise
3737
}

src/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"dependencies": {
33
"download": "^8.0.0",
4-
"tencent-component-toolkit": "^1.19.8",
4+
"tencent-component-toolkit": "^1.20.6",
55
"type": "^2.0.0"
66
}
77
}

0 commit comments

Comments
 (0)