@@ -17,10 +17,10 @@ const defaultConfig = {
1717}
1818
1919export default class APIToolkitMiddleware {
20- #topicName: string
20+ #topicName: string | undefined
2121 #topic: Topic | undefined
2222 #pubsub: PubSub | undefined
23- #project_id: string
23+ #project_id: string | undefined
2424 #config: APIToolkitConfig
2525 publishMessage : ( payload : Payload ) => void
2626 constructor ( ) {
@@ -30,13 +30,22 @@ export default class APIToolkitMiddleware {
3030 let pubsubClient : any
3131 if ( ! clientMetadata || configs . apiKey != '' ) {
3232 clientMetadata = this . getClientMetadata ( rootURL , configs . apiKey )
33- pubsubClient = new PubSub ( {
34- projectId : clientMetadata . pubsub_project_id ,
35- authClient : new PubSub ( ) . auth . fromJSON ( clientMetadata . pubsub_push_service_account ) ,
36- } )
33+ if ( clientMetadata ) {
34+ pubsubClient = new PubSub ( {
35+ projectId : clientMetadata . pubsub_project_id ,
36+ authClient : new PubSub ( ) . auth . fromJSON ( clientMetadata . pubsub_push_service_account ) ,
37+ } )
38+ const { topic_id, project_id } = clientMetadata
39+ this . #topicName = topic_id
40+ this . #pubsub = pubsubClient
41+ this . #project_id = project_id
42+ } else {
43+ this . #topicName = undefined
44+ this . #pubsub = pubsubClient
45+ this . #project_id = undefined
46+ }
3747 }
3848
39- const { topic_id, project_id } = clientMetadata
4049 if ( configs . debug ) {
4150 console . log ( 'apitoolkit: initialized successfully' )
4251 console . dir ( pubsubClient )
@@ -51,9 +60,6 @@ export default class APIToolkitMiddleware {
5160 )
5261 }
5362
54- this . #topicName = topic_id
55- this . #pubsub = pubsubClient
56- this . #project_id = project_id
5763 this . #config = configs
5864 if ( this . #pubsub && this . #topicName) {
5965 this . #topic = this . #pubsub?. topic ( this . #topicName)
@@ -116,7 +122,14 @@ export default class APIToolkitMiddleware {
116122 Accept : 'application/json' ,
117123 } ,
118124 } )
119- if ( ! resp . ok ) throw new Error ( `Error getting apitoolkit client_metadata ${ resp . status } ` )
125+ if ( ! resp . ok ) {
126+ if ( resp . status === 401 ) {
127+ throw new Error ( 'APIToolkit Error: Please check your API Key' )
128+ } else {
129+ console . error ( `Error getting apitoolkit client_metadata ${ resp . status } ` )
130+ }
131+ return
132+ }
120133 return resp . json ( ) as ClientMetadata
121134 }
122135
@@ -125,14 +138,14 @@ export default class APIToolkitMiddleware {
125138 const config = this . #config
126139 const client = this
127140 class middleware {
128- #project_id: string
141+ #project_id: string | undefined
129142 #config: APIToolkitConfig
130143 constructor ( ) {
131144 this . #project_id = project_id
132145 this . #config = config
133146 }
134147 public async handle ( { request, response } : HttpContext , next : NextFn ) {
135- if ( this . #config?. disable ) {
148+ if ( this . #config?. disable || ! this . #project_id ) {
136149 await next ( )
137150 return
138151 }
0 commit comments