@@ -3,20 +3,52 @@ import ChangelogTopic from './ChangelogTopic';
33class ChangelogService {
44 /**
55 * @param {string } apiBase
6+ * @param {string } fallbackApiBase
67 */
7- constructor ( apiBase ) {
8+ constructor ( apiBase , fallbackApiBase ) {
89 /** @type {string } */
910 this . apiBase = apiBase ;
11+ /** @type {string } */
12+ this . fallbackApiBase = fallbackApiBase ;
13+ /** @type {string|null } */
14+ this . currentApiBase = null ;
15+ }
16+
17+ /**
18+ * Checks the availability of the primary and fallback API bases, and returns the one that is reachable.
19+ * @throws {Error } if neither the primary nor the fallback API base is reachable
20+ * @returns {Promise<string> } the reachable API base URL
21+ */
22+ async getApiBase ( ) {
23+ if ( this . currentApiBase !== null ) {
24+ return this . currentApiBase ;
25+ }
26+ try {
27+ const response = await fetch ( `${ this . apiBase } /changelog-proxy` ) ;
28+ if ( response . ok ) {
29+ this . currentApiBase = this . apiBase ;
30+ }
31+ } catch ( error ) {
32+ this . currentApiBase = this . fallbackApiBase ;
33+ }
34+ if ( this . currentApiBase === null ) {
35+ const response = await fetch ( `${ this . fallbackApiBase } /changelog-proxy` ) ;
36+ if ( response . ok ) {
37+ this . currentApiBase = this . fallbackApiBase ;
38+ }
39+ }
40+ return this . currentApiBase ;
1041 }
1142
1243 /**
1344 * @param {string } changelogUrl
1445 * @returns {Promise<ChangelogTopic[]> }
1546 */
1647 async loadTopics ( changelogUrl ) {
48+ const apiBase = await this . getApiBase ( ) ;
1749 const d = new Date ( ) . toISOString ( ) . split ( ':' ) ;
1850 const cacheBuster = `${ d [ 0 ] . replace ( / [ ^ \d ] / g, '' ) } ${ Math . floor ( d [ 1 ] / 15 ) } ` ;
19- const url = `${ this . apiBase + changelogUrl } ?_=${ cacheBuster } ` ;
51+ const url = `${ apiBase + changelogUrl } ?_=${ cacheBuster } ` ;
2052 const response = await fetch ( url ) ;
2153 const json = await response . json ( ) ;
2254 return json . topic_list . topics . map ( ( data ) => new ChangelogTopic ( data ) ) ;
@@ -27,8 +59,9 @@ class ChangelogService {
2759 * @returns {Promise<ChangelogTopic> }
2860 */
2961 async loadTopic ( topicSlugId ) {
62+ const apiBase = await this . getApiBase ( ) ;
3063 if ( topicSlugId . match ( / r m - \d + / ) ) {
31- const url = `${ this . apiBase } /changelog.json` ;
64+ const url = `${ apiBase } /changelog.json` ;
3265 const response = await fetch ( url ) ;
3366 const json = await response . json ( ) ;
3467 const topicJson = json . topic_list . topics . filter (
@@ -39,7 +72,7 @@ class ChangelogService {
3972 }
4073 }
4174
42- const url = `${ this . apiBase } /changelog/api/t/${ topicSlugId } .json` ;
75+ const url = `${ apiBase } /changelog/api/t/${ topicSlugId } .json` ;
4376 const response = await fetch ( url ) ;
4477 const json = await response . json ( ) ;
4578 if ( ! json . errors || json . errors . length === 0 ) {
0 commit comments