File tree Expand file tree Collapse file tree 3 files changed +33
-7
lines changed Expand file tree Collapse file tree 3 files changed +33
-7
lines changed Original file line number Diff line number Diff 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
163163const 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
180206MIT License
Original file line number Diff line number Diff 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}
Original file line number Diff line number Diff line change 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}
You can’t perform that action at this time.
0 commit comments