Skip to content

Commit

Permalink
fix: add sls initialize before creating server
Browse files Browse the repository at this point in the history
  • Loading branch information
yugasun committed Dec 28, 2020
1 parent b2ef160 commit 9ce2692
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 6 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,32 @@ TENCENT_SECRET_ID=123
TENCENT_SECRET_KEY=123
```

### slsInitialize 应用初始化

有些时候,Koa 服务在启动前,需要进行一个初始化操作,比如数据库建连,就可以通过在 Koa 实例对象上添加 `slsInitialize` 函数来实现,如下:

```js
const Koa = require('koa')
const mysql = require('mysql2/promise')

const app = new Koa()

// ...

app.slsInitialize = async () => {
app.db = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test'
})
}

// don't forget to export!
module.exports = app
```

这样应用部署到云函数后,在函数服务逻辑执行前,会先执行 `slsInitialize()` 函数,来初始化数据库连接。

### 还支持哪些组件?

可以在 [Serverless Components](https://github.com/serverless/components) repo 中查询更多组件的信息。
Expand Down
2 changes: 1 addition & 1 deletion serverless.component.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: koa
version: 0.3.1
version: 0.3.2
author: 'Tencent Cloud, Inc.'
org: 'Tencent Cloud, Inc.'
description: Deploy a serverless Koa.js application onto Tencent SCF and API Gateway.
Expand Down
8 changes: 4 additions & 4 deletions src/_shims/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ exports.handler = async (event, context) => {
app.request.__SLS_EVENT__ = event
app.request.__SLS_CONTEXT__ = context

if (app.slsInitialize && typeof app.slsInitialize === 'function') {
await app.slsInitialize()
}

// cache server, not create repeatly
if (!server) {
server = createServer(app.callback(), null, app.binaryTypes || [])
Expand All @@ -26,10 +30,6 @@ exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop =
app.callbackWaitsForEmptyEventLoop === true ? true : false

if (app.slsInitialize && typeof app.slsInitialize === 'function') {
await app.slsInitialize()
}

const result = await proxy(server, event, context, 'PROMISE')
return result.promise
}
2 changes: 1 addition & 1 deletion src/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"dependencies": {
"download": "^8.0.0",
"tencent-component-toolkit": "^1.19.8",
"tencent-component-toolkit": "^1.20.6",
"type": "^2.1.0"
}
}

0 comments on commit 9ce2692

Please sign in to comment.