chore: convert some promises to async/await

Signed-off-by: Martin d'Allens <martin.dallens@liberty-rider.com>
This commit is contained in:
Martin d'Allens 2023-11-20 22:39:14 +01:00
parent 526766c8f4
commit 345b831edd
5 changed files with 79 additions and 81 deletions

View file

@ -241,7 +241,7 @@ const StartWithInputFile = async (inputFile) => {
} }
}; };
fs.stat(path.resolve(opts.config), (err, stats) => { fs.stat(path.resolve(opts.config), async (err, stats) => {
if (err || !stats.isFile() || stats.size === 0) { if (err || !stats.isFile() || stats.size === 0) {
let inputFile; let inputFile;
if (opts.file) { if (opts.file) {
@ -274,21 +274,22 @@ fs.stat(path.resolve(opts.config), (err, stats) => {
const writer = fs.createWriteStream(filename); const writer = fs.createWriteStream(filename);
console.log(`No input file found`); console.log(`No input file found`);
console.log(`[DEMO] Downloading sample data (${filename}) from ${url}`); console.log(`[DEMO] Downloading sample data (${filename}) from ${url}`);
axios({
try {
const response = await axios({
url, url,
method: 'GET', method: 'GET',
responseType: 'stream', responseType: 'stream',
}) });
.then((response) => {
response.data.pipe(writer); response.data.pipe(writer);
writer.on('finish', () => StartWithInputFile(filename)); writer.on('finish', () => StartWithInputFile(filename));
writer.on('error', (err) => writer.on('error', (err) =>
console.error(`Error writing file: ${err}`), console.error(`Error writing file: ${err}`),
); );
}) } catch (error) {
.catch((error) => {
console.error(`Error downloading file: ${error}`); console.error(`Error downloading file: ${error}`);
}); }
} }
} }
} else { } else {

View file

@ -4,7 +4,7 @@ import express from 'express';
import { getFontsPbf, listFonts } from './utils.js'; import { getFontsPbf, listFonts } from './utils.js';
export const serve_font = (options, allowedFonts) => { export const serve_font = async (options, allowedFonts) => {
const app = express().disable('x-powered-by'); const app = express().disable('x-powered-by');
const lastModified = new Date().toUTCString(); const lastModified = new Date().toUTCString();
@ -13,25 +13,29 @@ export const serve_font = (options, allowedFonts) => {
const existingFonts = {}; const existingFonts = {};
app.get('/fonts/:fontstack/:range([\\d]+-[\\d]+).pbf', (req, res, next) => { app.get(
'/fonts/:fontstack/:range([\\d]+-[\\d]+).pbf',
async (req, res, next) => {
const fontstack = decodeURI(req.params.fontstack); const fontstack = decodeURI(req.params.fontstack);
const range = req.params.range; const range = req.params.range;
getFontsPbf( try {
const concatenated = await getFontsPbf(
options.serveAllFonts ? null : allowedFonts, options.serveAllFonts ? null : allowedFonts,
fontPath, fontPath,
fontstack, fontstack,
range, range,
existingFonts, existingFonts,
).then( );
(concated) => {
res.header('Content-type', 'application/x-protobuf'); res.header('Content-type', 'application/x-protobuf');
res.header('Last-Modified', lastModified); res.header('Last-Modified', lastModified);
return res.send(concated); return res.send(concatenated);
} catch (err) {
res.status(400).header('Content-Type', 'text/plain').send(err);
}
}, },
(err) => res.status(400).header('Content-Type', 'text/plain').send(err),
); );
});
app.get('/fonts.json', (req, res, next) => { app.get('/fonts.json', (req, res, next) => {
res.header('Content-type', 'application/json'); res.header('Content-type', 'application/json');
@ -40,8 +44,7 @@ export const serve_font = (options, allowedFonts) => {
); );
}); });
return listFonts(options.paths.fonts).then((fonts) => { const fonts = await listFonts(options.paths.fonts);
Object.assign(existingFonts, fonts); Object.assign(existingFonts, fonts);
return app; return app;
});
}; };

View file

@ -524,7 +524,7 @@ const existingFonts = {};
let maxScaleFactor = 2; let maxScaleFactor = 2;
export const serve_rendered = { export const serve_rendered = {
init: (options, repo) => { init: async (options, repo) => {
maxScaleFactor = Math.min(Math.floor(options.maxScaleFactor || 3), 9); maxScaleFactor = Math.min(Math.floor(options.maxScaleFactor || 3), 9);
let scalePattern = ''; let scalePattern = '';
for (let i = 2; i <= maxScaleFactor; i++) { for (let i = 2; i <= maxScaleFactor; i++) {
@ -909,10 +909,9 @@ export const serve_rendered = {
return res.send(info); return res.send(info);
}); });
return listFonts(options.paths.fonts).then((fonts) => { const fonts = await listFonts(options.paths.fonts);
Object.assign(existingFonts, fonts); Object.assign(existingFonts, fonts);
return app; return app;
});
}, },
add: async (options, repo, params, id, publicUrl, dataResolver) => { add: async (options, repo, params, id, publicUrl, dataResolver) => {
const map = { const map = {
@ -941,20 +940,19 @@ export const serve_rendered = {
const parts = req.url.split('/'); const parts = req.url.split('/');
const fontstack = unescape(parts[2]); const fontstack = unescape(parts[2]);
const range = parts[3].split('.')[0]; const range = parts[3].split('.')[0];
getFontsPbf(
try {
const concatenated = await getFontsPbf(
null, null,
options.paths[protocol], options.paths[protocol],
fontstack, fontstack,
range, range,
existingFonts, existingFonts,
).then(
(concated) => {
callback(null, { data: concated });
},
(err) => {
callback(err, { data: null });
},
); );
callback(null, { data: concatenated });
} catch (err) {
callback(err, { data: null });
}
} else if (protocol === 'mbtiles' || protocol === 'pmtiles') { } else if (protocol === 'mbtiles' || protocol === 'pmtiles') {
const parts = req.url.split('/'); const parts = req.url.split('/');
const sourceId = parts[2]; const sourceId = parts[2];
@ -1296,7 +1294,8 @@ export const serve_rendered = {
} }
} }
const renderersReadyPromise = Promise.all(queue).then(() => { await Promise.all(queue);
// standard and @2x tiles are much more usual -> default to larger pools // standard and @2x tiles are much more usual -> default to larger pools
const minPoolSizes = options.minRendererPoolSizes || [8, 4, 2]; const minPoolSizes = options.minRendererPoolSizes || [8, 4, 2];
const maxPoolSizes = options.maxRendererPoolSizes || [16, 8, 4]; const maxPoolSizes = options.maxRendererPoolSizes || [16, 8, 4];
@ -1313,9 +1312,6 @@ export const serve_rendered = {
maxPoolSize, maxPoolSize,
); );
} }
});
return renderersReadyPromise;
}, },
remove: (repo, id) => { remove: (repo, id) => {
const item = repo[id]; const item = repo[id];

View file

@ -141,11 +141,8 @@ function start(opts) {
// Load all available icons into a settings object // Load all available icons into a settings object
startupPromises.push( startupPromises.push(
new Promise((resolve) => {
getFiles(paths.icons).then((files) => { getFiles(paths.icons).then((files) => {
paths.availableIcons = files; paths.availableIcons = files;
resolve();
});
}), }),
); );

View file

@ -139,7 +139,7 @@ const getFontPbf = (allowedFonts, fontPath, name, range, fallbacks) =>
} }
}); });
export const getFontsPbf = ( export const getFontsPbf = async (
allowedFonts, allowedFonts,
fontPath, fontPath,
names, names,
@ -160,7 +160,8 @@ export const getFontsPbf = (
); );
} }
return Promise.all(queue).then((values) => glyphCompose.combine(values)); const values = await Promise.all(queue);
return glyphCompose.combine(values);
}; };
export const listFonts = async (fontPath) => { export const listFonts = async (fontPath) => {