@@ -56,6 +56,8 @@ export interface BraintreePaymentSessionData {
56
56
braintreeTransaction ?: Transaction ;
57
57
}
58
58
59
+ const buildTokenCacheKey = ( customerId : string ) => `braintree:clientToken:${ customerId } ` ;
60
+
59
61
class BraintreeBase extends AbstractPaymentProvider < BraintreeOptions > {
60
62
identifier = 'braintree' ;
61
63
protected readonly options_ : BraintreeOptions ;
@@ -74,21 +76,15 @@ class BraintreeBase extends AbstractPaymentProvider<BraintreeOptions> {
74
76
}
75
77
76
78
async saveClientTokenToCache ( clientToken : string , customerId : string , expiresOn : number ) : Promise < void > {
77
- if ( ! customerId ) {
78
- return ;
79
- }
80
- if ( ! clientToken ) {
81
- return ;
82
- }
83
- const expiryTime = expiresOn * 1000 - Math . floor ( Date . now ( ) ) - 1000 ;
84
- if ( expiryTime < 0 ) {
85
- return ;
86
- }
87
- await this . cache . set ( `braintree:clientToken:${ customerId } ` , clientToken , Math . floor ( expiryTime / 1000 ) ) ;
79
+ const expiryTime = expiresOn * 1000 - Math . floor ( Date . now ( ) ) - 1000 ;
80
+
81
+ if ( ! customerId || ! clientToken || expiryTime < 0 ) return ;
82
+
83
+ await this . cache . set ( buildTokenCacheKey ( customerId ) , clientToken , Math . floor ( expiryTime / 1000 ) ) ;
88
84
}
89
85
90
86
async getClientTokenFromCache ( customerId : string ) : Promise < string | null > {
91
- const token = ( await this . cache . get ( `braintree:clientToken: ${ customerId } ` ) ) as string | null ;
87
+ const token = ( await this . cache . get ( buildTokenCacheKey ( customerId ) ) ) as string | null ;
92
88
return token ;
93
89
}
94
90
@@ -97,16 +93,17 @@ class BraintreeBase extends AbstractPaymentProvider<BraintreeOptions> {
97
93
const generatedToken = await this . gateway . clientToken . generate ( { } ) ;
98
94
return generatedToken . clientToken ;
99
95
}
96
+
100
97
const token = await this . getClientTokenFromCache ( customerId ) ;
101
- if ( token ) {
102
- return token ;
103
- }
98
+
99
+ if ( token ) return token ;
100
+
104
101
const generatedToken = await this . gateway . clientToken . generate ( { } ) ;
105
- const defaultExpiryTime = Math . floor ( Date . now ( ) / 1000 ) + 24 * 3600 * 1000 ; // 24 hours default
102
+ const defaultExpiryTime = Math . floor ( Date . now ( ) / 1000 ) + 24 * 3600 * 1000 ; // 24 hours default
103
+
106
104
await this . saveClientTokenToCache ( generatedToken . clientToken , customerId , defaultExpiryTime ) ;
107
105
return generatedToken . clientToken ;
108
106
}
109
-
110
107
111
108
private async parsePaymentSessionData ( data : Record < string , unknown > ) : Promise < BraintreePaymentSessionData > {
112
109
return {
0 commit comments