forked from open-telemetry/opentelemetry-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcharge.js
78 lines (65 loc) · 2.59 KB
/
charge.js
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
const {context, propagation, trace, metrics} = require('@opentelemetry/api');
const cardValidator = require('simple-card-validator');
const { v4: uuidv4 } = require('uuid');
const { OpenFeature } = require('@openfeature/server-sdk');
const { FlagdProvider} = require('@openfeature/flagd-provider');
const flagProvider = new FlagdProvider();
const logger = require('./logger');
const tracer = trace.getTracer('paymentservice');
const meter = metrics.getMeter('paymentservice');
const transactionsCounter = meter.createCounter('app.payment.transactions')
module.exports.charge = async request => {
const span = tracer.startSpan('charge');
await OpenFeature.setProviderAndWait(flagProvider);
if (await OpenFeature.getClient().getBooleanValue("paymentServiceFailure", false)) {
throw new Error("PaymentService Fail Feature Flag Enabled");
}
const {
creditCardNumber: number,
creditCardExpirationYear: year,
creditCardExpirationMonth: month
} = request.creditCard;
const currentMonth = new Date().getMonth() + 1;
const currentYear = new Date().getFullYear();
const lastFourDigits = number.substr(-4);
const transactionId = uuidv4();
const card = cardValidator(number);
const { card_type: cardType, valid } = card.getCardDetails();
span.setAttributes({
'app.payment.card_type': cardType,
'app.payment.card_valid': valid
});
if (!valid) {
throw new Error('Credit card info is invalid.');
}
if (!['visa', 'mastercard'].includes(cardType)) {
throw new Error(`Sorry, we cannot process ${cardType} credit cards. Only VISA or MasterCard is accepted.`);
}
if ((currentYear * 12 + currentMonth) > (year * 12 + month)) {
throw new Error(`The credit card (ending ${lastFourDigits}) expired on ${month}/${year}.`);
}
// check baggage for synthetic_request=true, and add charged attribute accordingly
const baggage = propagation.getBaggage(context.active());
if (baggage && baggage.getEntry("synthetic_request") && baggage.getEntry("synthetic_request").value === "true") {
span.setAttribute('app.payment.charged', false);
} else {
span.setAttribute('app.payment.charged', true);
}
span.end();
const { units, nanos, currencyCode } = request.amount;
logger.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "Transaction complete.",
attributes: {
transactionId,
cardType,
lastFourDigits,
amount: { units, nanos, currencyCode },
},
});
transactionsCounter.add(1, {"app.payment.currency": currencyCode})
return { transactionId }
}