1
- import jsonwebtoken from "jsonwebtoken"
1
+ import jsonwebtoken from "jsonwebtoken" ;
2
2
3
- const API_TOKEN_TTL_SECONDS = 3 * 60
4
- const CACHE_TTL_SECONDS = API_TOKEN_TTL_SECONDS - 30
3
+ const API_TOKEN_TTL_SECONDS = 3 * 60 ;
4
+ const CACHE_TTL_SECONDS = API_TOKEN_TTL_SECONDS - 30 ;
5
5
const tokenCache : {
6
- [ key : string ] : {
7
- token : string ,
8
- createAt : number
9
- }
10
- } = { }
6
+ [ key : string ] : {
7
+ token : string ;
8
+ createAt : number ;
9
+ } ;
10
+ } = { } ;
11
11
12
12
export const encodeApiKey = ( apiSecretKey ?: string , cache = true ) : string => {
13
- if ( ! apiSecretKey ) throw new Error ( "Api_key is required" ) ;
14
- try {
15
- if ( tokenCache [ apiSecretKey ] && Date . now ( ) - tokenCache [ apiSecretKey ] . createAt < ( CACHE_TTL_SECONDS * 1000 ) ) {
16
- return tokenCache [ apiSecretKey ] . token
17
- }
13
+ if ( ! apiSecretKey ) throw new Error ( "Api_key is required" ) ;
14
+ try {
15
+ if (
16
+ tokenCache [ apiSecretKey ] &&
17
+ Date . now ( ) - tokenCache [ apiSecretKey ] . createAt < CACHE_TTL_SECONDS * 1000
18
+ ) {
19
+ return tokenCache [ apiSecretKey ] . token ;
20
+ }
18
21
19
- const [ apiKey , secret ] = apiSecretKey . split ( "." )
20
- const payload = {
21
- api_key : apiKey ,
22
- exp : Math . round ( Date . now ( ) * 1000 ) + API_TOKEN_TTL_SECONDS * 1000 ,
23
- timestamp : Math . round ( Date . now ( ) * 1000 ) ,
24
- }
25
- // algorithm = "HS256", headers = { "alg": "HS256", "sign_type": "SIGN" }
26
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
27
- // @ts -ignore
28
- const ret = jsonwebtoken . sign ( payload , secret , {
29
- algorithm : "HS256" ,
30
- header : { alg : "HS256" , sign_type : "SIGN" }
31
- } )
32
- if ( cache ) {
33
- tokenCache [ apiSecretKey ] = {
34
- token : ret ,
35
- createAt : Date . now ( )
36
- }
37
- }
38
- return ret
39
- } catch ( e ) {
40
- throw new Error ( "invalid api_key" )
22
+ const [ apiKey , secret ] = apiSecretKey . split ( "." ) ;
23
+ const payload = {
24
+ api_key : apiKey ,
25
+ exp : Math . round ( Date . now ( ) * 1000 ) + API_TOKEN_TTL_SECONDS * 1000 ,
26
+ timestamp : Math . round ( Date . now ( ) * 1000 ) ,
27
+ } ;
28
+ // algorithm = "HS256", headers = { "alg": "HS256", "sign_type": "SIGN" }
29
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
30
+ // @ts -ignore
31
+ const ret = jsonwebtoken . sign ( payload , secret , {
32
+ algorithm : "HS256" ,
33
+ header : { alg : "HS256" , sign_type : "SIGN" } ,
34
+ } ) ;
35
+ if ( cache ) {
36
+ tokenCache [ apiSecretKey ] = {
37
+ token : ret ,
38
+ createAt : Date . now ( ) ,
39
+ } ;
41
40
}
42
- }
41
+ return ret ;
42
+ } catch ( e ) {
43
+ throw new Error ( "invalid api_key" ) ;
44
+ }
45
+ } ;
0 commit comments