-
-
Notifications
You must be signed in to change notification settings - Fork 654
/
invoke-func.ts
98 lines (84 loc) · 2.57 KB
/
invoke-func.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* @Author: Maslow<wangfugen@126.com>
* @Date: 2021-07-30 10:30:29
* @LastEditTime: 2022-02-03 00:59:07
* @Description:
*/
import { Request, Response } from 'express'
import { FunctionContext } from '../support/function-engine'
import Config from '../config'
import { logger } from '../support/logger'
import { addFunctionLog } from '../support/function-log'
import { CloudFunction } from '../support/function-engine'
const DEFAULT_FUNCTION_NAME = '__default__'
/**
* Handler of invoking cloud function
*/
export async function handleInvokeFunction(req: Request, res: Response) {
const requestId = req['requestId']
const func_name = req.params?.name
// load function data from db
let funcData = await CloudFunction.getFunctionByName(func_name)
if (!funcData) {
if (func_name === 'healthz') {
return res.status(200).send('ok')
}
// load default function from db
funcData = await CloudFunction.getFunctionByName(DEFAULT_FUNCTION_NAME)
if (!funcData) {
return res.status(404).send('Not Found')
}
}
const func = new CloudFunction(funcData)
// reject while no HTTP enabled
if (!func.enableHTTP) {
return res.status(404).send('Not Found')
}
// reject while func was disabled
if (1 !== func.status) {
return res.status(404).send('Not Found')
}
try {
// execute the func
const ctx: FunctionContext = {
query: req.query,
files: req.files as any,
body: req.body,
headers: req.headers,
method: req.method,
auth: req['auth'],
requestId,
response: res,
}
const result = await func.invoke(ctx)
// log this execution to db
if (Config.ENABLE_CLOUD_FUNCTION_LOG === 'always') {
await addFunctionLog({
requestId: requestId,
method: req.method,
func_id: func.id,
func_name: func_name,
logs: result.logs,
time_usage: result.time_usage,
created_by: req['auth']?.uid,
data: result.data,
error: result.error,
debug: false
})
}
if (result.error) {
logger.error(requestId, `invoke function ${func_name} invoke error: `, result)
return res.status(400).send({
error: 'invoke cloud function got error, please check the function logs',
requestId
})
}
logger.trace(requestId, `invoke function ${func_name} invoke success: `, result)
if (res.writableEnded === false) {
return res.send(result.data)
}
} catch (error) {
logger.error(requestId, 'failed to invoke error', error)
return res.status(500).send('Internal Server Error')
}
}