|
| 1 | +/* |
| 2 | +Copyright 2018 New Vector Ltd |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import Promise from 'bluebird'; |
| 18 | +import request from 'browser-request'; |
| 19 | + |
| 20 | +export async function getVectorConfig(relativeLocation) { |
| 21 | + if (relativeLocation === undefined) relativeLocation = ''; |
| 22 | + if (relativeLocation !== '' && !relativeLocation.endsWith('/')) relativeLocation += '/'; |
| 23 | + try { |
| 24 | + const configJson = await getConfig(`${relativeLocation}config.${document.domain}.json`); |
| 25 | + // 404s succeed with an empty json config, so check that there are keys |
| 26 | + if (Object.keys(configJson).length === 0) { |
| 27 | + throw new Error(); // throw to enter the catch |
| 28 | + } |
| 29 | + return configJson; |
| 30 | + } catch (e) { |
| 31 | + return await getConfig(relativeLocation + "config.json"); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function getConfig(configJsonFilename) { |
| 36 | + let deferred = Promise.defer(); |
| 37 | + |
| 38 | + request( |
| 39 | + { method: "GET", url: configJsonFilename }, |
| 40 | + (err, response, body) => { |
| 41 | + if (err || response.status < 200 || response.status >= 300) { |
| 42 | + // Lack of a config isn't an error, we should |
| 43 | + // just use the defaults. |
| 44 | + // Also treat a blank config as no config, assuming |
| 45 | + // the status code is 0, because we don't get 404s |
| 46 | + // from file: URIs so this is the only way we can |
| 47 | + // not fail if the file doesn't exist when loading |
| 48 | + // from a file:// URI. |
| 49 | + if (response) { |
| 50 | + if (response.status == 404 || (response.status == 0 && body == '')) { |
| 51 | + deferred.resolve({}); |
| 52 | + } |
| 53 | + } |
| 54 | + deferred.reject({err: err, response: response}); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + // We parse the JSON ourselves rather than use the JSON |
| 59 | + // parameter, since this throws a parse error on empty |
| 60 | + // which breaks if there's no config.json and we're |
| 61 | + // loading from the filesystem (see above). |
| 62 | + deferred.resolve(JSON.parse(body)); |
| 63 | + } |
| 64 | + ); |
| 65 | + |
| 66 | + return deferred.promise; |
| 67 | +} |
0 commit comments