forked from kyma-project/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
call-ec-function.yml
111 lines (101 loc) · 2.81 KB
/
call-ec-function.yml
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
99
100
101
102
103
104
105
106
107
108
109
110
111
apiVersion: kubeless.io/v1beta1
kind: Function
metadata:
finalizers:
- kubeless.io/function
labels:
created-by: kubeless
function: calculate-promotion
example: call-ec
name: calculate-promotion
spec:
deployment:
spec:
template:
spec:
containers:
- env:
- name: EC_SVC_URL
value: target_url
deps: |
{
"name": "calculate-promotion",
"version": "0.0.1",
"dependencies": {
"request": "^2.85.0"
}
}
function: |-
const request = require('request');
const USER_ID_PARAM = "user-id";
const ORDER_THRESHOLD_PARAM = "threshold";
const ACCESS_TOKEN_HEADER = "access-token";
module.exports = {
'calculate-promotion': (event, context) => {
return new Promise((resolve, reject) => {
console.log("Starting calculate-promotion lambda function")
const request = event.extensions.request;
const threshold = request.query[ORDER_THRESHOLD_PARAM];
if (validateRequest(request)) {
const accessToken = request.headers[ACCESS_TOKEN_HEADER];
const userId = request.query[USER_ID_PARAM];
const url = `${process.env.EC_SVC_URL}/rest/v2/electronics/users/${userId}/orders`;
const options = {
url: url,
headers: {
[ACCESS_TOKEN_HEADER]: `Bearer ${accessToken}`
},
json: true
};
calculatePromotion(options, threshold, resolve, reject);
} else {
reject({
stack: "user-id and threshold params need to be specified"
})
}
})
}
};
function validateRequest(request) {
return request.query[USER_ID_PARAM] != undefined && request.query[ORDER_THRESHOLD_PARAM] != undefined;
}
function calculatePromotion(options, threshold, resolve, reject) {
request.get(options, (error, response, body) => {
if (!error) {
if (response.statusCode == 200) {
console.log('Getting orders from EC succeeded.');
const s = calculateTotalPrice(body.orders);
resolve({promotion: s > threshold});
}
else {
reject({
stack: `Getting orders returned unexpected status: ${response.statusCode}.`
})
}
} else {
reject({
stack: "Failed to get orders."
})
}
})
}
function calculateTotalPrice(orders) {
return orders.reduce((sum, order) => sum + order.total.value, 0)
}
function-content-type: text
handler: call-ec.calculate-promotion
horizontalPodAutoscaler:
spec:
maxReplicas: 0
runtime: nodejs8
service:
ports:
- name: http-function-port
port: 8080
protocol: TCP
targetPort: 8080
selector:
created-by: kubeless
function: calculate-promotion
type: ClusterIP
timeout: "180"