Skip to content

Commit 9ce2692

Browse files
committed
fix: add sls initialize before creating server
1 parent b2ef160 commit 9ce2692

File tree

4 files changed

+32
-6
lines changed

4 files changed

+32
-6
lines changed

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,32 @@ TENCENT_SECRET_ID=123
102102
TENCENT_SECRET_KEY=123
103103
```
104104

105+
### slsInitialize 应用初始化
106+
107+
有些时候,Koa 服务在启动前,需要进行一个初始化操作,比如数据库建连,就可以通过在 Koa 实例对象上添加 `slsInitialize` 函数来实现,如下:
108+
109+
```js
110+
const Koa = require('koa')
111+
const mysql = require('mysql2/promise')
112+
113+
const app = new Koa()
114+
115+
// ...
116+
117+
app.slsInitialize = async () => {
118+
app.db = await mysql.createConnection({
119+
host: 'localhost',
120+
user: 'root',
121+
database: 'test'
122+
})
123+
}
124+
125+
// don't forget to export!
126+
module.exports = app
127+
```
128+
129+
这样应用部署到云函数后,在函数服务逻辑执行前,会先执行 `slsInitialize()` 函数,来初始化数据库连接。
130+
105131
### 还支持哪些组件?
106132

107133
可以在 [Serverless Components](https://github.com/serverless/components) repo 中查询更多组件的信息。

serverless.component.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
name: koa
2-
version: 0.3.1
2+
version: 0.3.2
33
author: 'Tencent Cloud, Inc.'
44
org: 'Tencent Cloud, Inc.'
55
description: Deploy a serverless Koa.js application onto Tencent SCF and API Gateway.

src/_shims/handler.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ exports.handler = async (event, context) => {
1818
app.request.__SLS_EVENT__ = event
1919
app.request.__SLS_CONTEXT__ = context
2020

21+
if (app.slsInitialize && typeof app.slsInitialize === 'function') {
22+
await app.slsInitialize()
23+
}
24+
2125
// cache server, not create repeatly
2226
if (!server) {
2327
server = createServer(app.callback(), null, app.binaryTypes || [])
@@ -26,10 +30,6 @@ exports.handler = async (event, context) => {
2630
context.callbackWaitsForEmptyEventLoop =
2731
app.callbackWaitsForEmptyEventLoop === true ? true : false
2832

29-
if (app.slsInitialize && typeof app.slsInitialize === 'function') {
30-
await app.slsInitialize()
31-
}
32-
3333
const result = await proxy(server, event, context, 'PROMISE')
3434
return result.promise
3535
}

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.1.0"
66
}
77
}

0 commit comments

Comments
 (0)