16
16
17
17
import * as admin from "firebase-admin" ;
18
18
import * as functions from "firebase-functions" ;
19
- import axios , { AxiosInstance } from "axios" ;
20
19
21
20
import { FirestoreUrlShortener } from "./abstract-shortener" ;
22
21
import config from "./config" ;
23
22
import * as logs from "./logs" ;
24
23
import * as events from "./events" ;
24
+
25
+ interface BitlyResponse {
26
+ link ?: string ;
27
+ }
28
+
25
29
class FirestoreBitlyUrlShortener extends FirestoreUrlShortener {
26
- private instance : AxiosInstance ;
30
+ private bitlyAccessToken : string ;
27
31
28
32
constructor (
29
33
urlFieldName : string ,
30
34
shortUrlFieldName : string ,
31
35
bitlyAccessToken : string
32
36
) {
33
37
super ( urlFieldName , shortUrlFieldName ) ;
34
- this . instance = axios . create ( {
35
- headers : {
36
- Authorization : `Bearer ${ bitlyAccessToken } ` ,
37
- "Content-Type" : "application/json" ,
38
- } ,
39
- baseURL : "https://api-ssl.bitly.com/v4/" ,
40
- } ) ;
41
-
38
+ this . bitlyAccessToken = bitlyAccessToken ;
42
39
logs . init ( ) ;
43
40
}
44
41
@@ -49,15 +46,27 @@ class FirestoreBitlyUrlShortener extends FirestoreUrlShortener {
49
46
logs . shortenUrl ( url ) ;
50
47
51
48
try {
52
- const response : any = await this . instance . post ( "bitlinks" , {
53
- long_url : url ,
49
+ const response = await fetch ( "https://api-ssl.bitly.com/v4/bitlinks" , {
50
+ method : "POST" ,
51
+ headers : {
52
+ Authorization : `Bearer ${ this . bitlyAccessToken } ` ,
53
+ "Content-Type" : "application/json" ,
54
+ } ,
55
+ body : JSON . stringify ( { long_url : url } ) ,
54
56
} ) ;
55
57
56
- const { link } = response . data ;
58
+ if ( ! response . ok ) {
59
+ throw new Error ( `Error shortening URL: ${ response . statusText } ` ) ;
60
+ }
57
61
58
- logs . shortenUrlComplete ( link ) ;
62
+ const data : BitlyResponse = await response . json ( ) ;
59
63
60
- await this . updateShortUrl ( snapshot , link ) ;
64
+ if ( data . link ) {
65
+ logs . shortenUrlComplete ( data . link ) ;
66
+ await this . updateShortUrl ( snapshot , data . link ) ;
67
+ } else {
68
+ throw new Error ( "Bitly response did not contain a link." ) ;
69
+ }
61
70
} catch ( err ) {
62
71
logs . error ( err ) ;
63
72
}
0 commit comments