Files
editor/src/libs/metadata.ts
Harel M b429bb16d7 Fix network issue (#944)
## Launch Checklist

<!-- Thanks for the PR! Feel free to add or remove items from the
checklist. -->
In case of non 200 response the font and glyphs metadata would return
the ajax error object instead of the default value.

Fixes #935

- #935

 - [x] Briefly describe the changes in this PR.
 - [x] Link to related issues.
- [x] Include before/after visuals or gifs if this PR includes visual
changes.
 - [ ] Write tests for all new functionality.
 - [x] Add an entry to `CHANGELOG.md` under the `## main` section.
2025-01-21 14:25:03 +00:00

45 lines
1.3 KiB
TypeScript

import npmurl from 'url'
function loadJSON(url: string, defaultValue: any, cb: (...args: any[]) => void) {
fetch(url, {
mode: 'cors',
credentials: "same-origin"
})
.then((response) => {
if (!response.ok) {
throw new Error('Failed to load metadata for ' + url);
}
return response.json();
})
.then((body) => {
cb(body)
})
.catch(() => {
console.warn('Can not load metadata for ' + url + ', using default value ' + defaultValue);
cb(defaultValue)
})
}
export function downloadGlyphsMetadata(urlTemplate: string, cb: (...args: any[]) => void) {
if(!urlTemplate) return cb([])
// Special handling because Tileserver GL serves the fontstacks metadata differently
// https://github.com/klokantech/tileserver-gl/pull/104#issuecomment-274444087
const urlObj = npmurl.parse(urlTemplate);
const normPathPart = '/%7Bfontstack%7D/%7Brange%7D.pbf';
if(urlObj.pathname === normPathPart) {
urlObj.pathname = '/fontstacks.json';
} else {
urlObj.pathname = urlObj.pathname!.replace(normPathPart, '.json');
}
const url = npmurl.format(urlObj);
loadJSON(url, [], cb)
}
export function downloadSpriteMetadata(baseUrl: string, cb: (...args: any[]) => void) {
if(!baseUrl) return cb([])
const url = baseUrl + '.json'
loadJSON(url, {}, glyphs => cb(Object.keys(glyphs)))
}