@@ -60,17 +60,40 @@ if (typeof window !== 'undefined') {
6060 async fetchVolumes ( query , options = { } ) {
6161 const maxResults = options . maxResults || 5 ;
6262 const extraParams = options . extraParams || '' ;
63- const apiKey = CONFIG . GOOGLE_BOOKS_API_KEY || CONFIG . GOOGLE_BOOKS_API_KEYS [ 0 ] || '' ;
64- if ( ! apiKey ) {
65- throw new Error ( 'Google Books API key is not configured' ) ;
63+ let keys = this . getKeys ( ) ;
64+ if ( keys . length === 0 && CONFIG . GOOGLE_BOOKS_API_KEY ) {
65+ keys = [ CONFIG . GOOGLE_BOOKS_API_KEY ] ;
6666 }
67- const url = `${ CONFIG . API_BASE } ?q=${ encodeURIComponent ( query ) } &maxResults=${ encodeURIComponent ( maxResults ) } &key=${ encodeURIComponent ( apiKey ) } ${ extraParams } ` ;
67+ const candidates = keys . length > 0 ? keys : [ null ] ;
68+ let lastError = null ;
6869
69- const response = await fetch ( url ) ;
70- if ( response . ok ) {
71- return await response . json ( ) ;
70+ for ( let index = 0 ; index < candidates . length ; index += 1 ) {
71+ const key = candidates [ index ] ;
72+ const keyParam = key ? `&key=${ encodeURIComponent ( key ) } ` : '' ;
73+ const url = `${ CONFIG . API_BASE } ?q=${ encodeURIComponent ( query ) } &maxResults=${ maxResults } ${ extraParams } ${ keyParam } ` ;
74+
75+ try {
76+ const response = await fetch ( url ) ;
77+ if ( response . ok ) {
78+ return await response . json ( ) ;
79+ }
80+
81+ const retryableStatuses = [ 429 , 403 , 503 ] ;
82+ if ( retryableStatuses . includes ( response . status ) && index < candidates . length - 1 ) {
83+ lastError = new Error ( `Google Books API returned ${ response . status } ` ) ;
84+ continue ;
85+ }
86+
87+ throw new Error ( `Google Books API returned ${ response . status } ` ) ;
88+ } catch ( error ) {
89+ lastError = error ;
90+ if ( index < candidates . length - 1 ) {
91+ continue ;
92+ }
93+ }
7294 }
73- throw new Error ( `Google Books API returned ${ response . status } ` ) ;
95+
96+ throw lastError || new Error ( 'Google Books request failed' ) ;
7497 }
7598 } ;
7699}
0 commit comments