fix: move fixUrl and allowedOptions to utils

Signed-off-by: acalcutt <acalcutt@techidiots.net>
This commit is contained in:
acalcutt 2024-04-23 14:29:43 -04:00
parent e9bb16936e
commit 452f9f0cc4
2 changed files with 34 additions and 34 deletions

View file

@ -7,44 +7,12 @@ import clone from 'clone';
import express from 'express'; import express from 'express';
import { validateStyleMin } from '@maplibre/maplibre-gl-style-spec'; import { validateStyleMin } from '@maplibre/maplibre-gl-style-spec';
import { getPublicUrl } from './utils.js'; import { fixUrl, allowedOptions } from './utils.js';
const httpTester = /^https?:\/\//i; const httpTester = /^https?:\/\//i;
const allowedSpriteScales = allowedOptions(['', '@2x', '@3x'], ''); const allowedSpriteScales = allowedOptions(['', '@2x', '@3x']);
const allowedSpriteFormats = allowedOptions(['png', 'json']); const allowedSpriteFormats = allowedOptions(['png', 'json']);
/**
*
* @param opts
* @param root0
* @param root0.defaultValue
*/
function allowedOptions(opts, { defaultValue } = {}) {
const values = Object.fromEntries(opts.map((key) => [key, key]));
return (value) => values[value] || defaultValue;
}
/**
*
* @param req
* @param url
* @param publicUrl
*/
function fixUrl(req, url, publicUrl) {
if (!url || typeof url !== 'string' || url.indexOf('local://') !== 0) {
return url;
}
const queryParams = [];
if (req.query.key) {
queryParams.unshift(`key=${encodeURIComponent(req.query.key)}`);
}
let query = '';
if (queryParams.length) {
query = `?${queryParams.join('&')}`;
}
return url.replace('local://', getPublicUrl(publicUrl, req)) + query;
}
export const serve_style = { export const serve_style = {
init: (options, repo) => { init: (options, repo) => {
const app = express().disable('x-powered-by'); const app = express().disable('x-powered-by');

View file

@ -6,6 +6,38 @@ import fs, { existsSync } from 'node:fs';
import clone from 'clone'; import clone from 'clone';
import glyphCompose from '@mapbox/glyph-pbf-composite'; import glyphCompose from '@mapbox/glyph-pbf-composite';
/**
* Restrict user input to an allowed set of options.
* @param opts
* @param root0
* @param root0.defaultValue
*/
export function allowedOptions(opts, { defaultValue } = {}) {
const values = Object.fromEntries(opts.map((key) => [key, key]));
return (value) => values[value] || defaultValue;
}
/**
* Replace local:// urls with public http(s):// urls
* @param req
* @param url
* @param publicUrl
*/
export function fixUrl(req, url, publicUrl) {
if (!url || typeof url !== 'string' || url.indexOf('local://') !== 0) {
return url;
}
const queryParams = [];
if (req.query.key) {
queryParams.unshift(`key=${encodeURIComponent(req.query.key)}`);
}
let query = '';
if (queryParams.length) {
query = `?${queryParams.join('&')}`;
}
return url.replace('local://', getPublicUrl(publicUrl, req)) + query;
}
/** /**
* Generate new URL object * Generate new URL object
* @param req * @param req