Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dt-6141: dynamically add city zones if config file flag assembleGeoJsonZones is true #4935

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions app/component/map/withGeojsonObjects.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ function withGeojsonObjects(Component) {
...props
}) {
const [geoJson, updateGeoJson] = useState(null);

useEffect(() => {
async function fetch() {
if (!isBrowser) {
Expand All @@ -37,7 +38,7 @@ function withGeojsonObjects(Component) {
if (Array.isArray(layers) && layers.length > 0) {
const json = await Promise.all(
layers.map(async ({ url, name, isOffByDefault, metadata }) => ({
url,
url: Array.isArray(url) ? url[0] : url,
isOffByDefault,
data: await getGeoJsonData(url, name, metadata),
})),
Expand All @@ -54,9 +55,14 @@ function withGeojsonObjects(Component) {
// adding geoJson to leafletObj moved to map
return <Component leafletObjs={leafletObjs} {...props} geoJson={geoJson} />;
}

const configShape = PropTypes.shape({
geoJson: PropTypes.shape({
layers: PropTypes.arrayOf(PropTypes.shape({ url: PropTypes.string })),
layers: PropTypes.arrayOf(
PropTypes.shape({
url: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
}),
),
layerConfigUrl: PropTypes.string,
}),
});
Expand All @@ -77,15 +83,10 @@ function withGeojsonObjects(Component) {
config: configShape,
})(GeojsonWrapper);

const WithStores = connectToStores(
WithContext,
[GeoJsonStore],
({ getStore }) => {
const { getGeoJsonConfig, getGeoJsonData } = getStore(GeoJsonStore);
return { getGeoJsonConfig, getGeoJsonData };
},
);
return WithStores;
return connectToStores(WithContext, [GeoJsonStore], ({ getStore }) => {
const { getGeoJsonConfig, getGeoJsonData } = getStore(GeoJsonStore);
return { getGeoJsonConfig, getGeoJsonData };
});
}

export default withGeojsonObjects;
23 changes: 19 additions & 4 deletions app/config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fs from 'fs';
import path from 'path';
import cloneDeep from 'lodash/cloneDeep';

import defaultConfig from './configurations/config.default';
import configMerger from './util/configMerger';
import { boundWithMinimumAreaSimple } from './util/geo-utils';
Expand Down Expand Up @@ -44,6 +45,7 @@ function addMetaData(config) {
break;
}
}

// read metadata template and modify it to match image assets generated by favicons-webpack-plugin
// eslint-disable-next-line no-param-reassign
config.metaData = cloneDeep(metaDataTemplate);
Expand Down Expand Up @@ -120,7 +122,6 @@ export function getNamedConfiguration(configName) {
addMetaData(config); // add dynamic metadata content

const appPathPrefix = config.URL.ASSET_URL || '';

if (config.geoJson && Array.isArray(config.geoJson.layers)) {
for (let i = 0; i < config.geoJson.layers.length; i++) {
const layer = config.geoJson.layers[i];
Expand All @@ -132,13 +133,27 @@ export function getNamedConfiguration(configName) {

configs[configName] = config;
}
if (!process.env.OIDC_CLIENT_ID && configs[configName].allowLogin) {
// inject zone geoJson if necessary
const conf = configs[configName];
if (conf.zoneGeoJson) {
if (conf.useAssembledGeoJsonZones) {
if (!conf.geoJson) {
conf.geoJson = conf.zoneGeoJson;
} else {
conf.geoJson.layers = conf.geoJson.layers.concat(
conf.zoneGeoJson.layers,
);
}
}
delete conf.zoneGeoJson; // not used directly so cleanup
}
if (!process.env.OIDC_CLIENT_ID && conf.allowLogin) {
return {
...configs[configName],
...conf,
allowLogin: false,
};
}
return configs[configName];
return conf;
}

export function getConfiguration(req) {
Expand Down
2 changes: 2 additions & 0 deletions app/configurations/config.kela.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export default configMerger(matkaConfig, {
],
},

useAssembledGeoJsonZones: true,

transportModes: {
citybike: {
availableForSelection: false,
Expand Down
33 changes: 23 additions & 10 deletions app/store/GeoJsonStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,33 @@ class GeoJsonStore extends Store {
if (!url) {
return undefined;
}

if (!this.geoJsonData[url]) {
const response = await getJson(url);
if (metadata) {
MapJSON(response, metadata);
let id;
let urlArr;
if (Array.isArray(url)) {
[id] = url;
urlArr = url;
} else {
id = url;
urlArr = [url];
}
if (!this.geoJsonData[id]) {
const responses = await Promise.all(urlArr.map(u => getJson(u)));
const mapped = responses.map(r => {
if (metadata) {
MapJSON(r, metadata);
}
return styleFeatures(r);
});
for (let i = 1; i < mapped.length; i++) {
mapped[0].features = mapped[0].features.concat(mapped[i].features);
}
const data = {
name: name || url,
data: styleFeatures(response),
name: name || id,
data: mapped[0],
};
this.geoJsonData[url] = data;
this.geoJsonData[id] = data;
}

return { ...this.geoJsonData[url] };
return { ...this.geoJsonData[id] };
};
}

Expand Down
70 changes: 67 additions & 3 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,14 @@ const expressStaticGzip = require('express-static-gzip');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const logger = require('morgan');
const { getJson } = require('../app/util/xhrPromise');
const { retryFetch } = require('../app/util/fetchUtils');
const config = require('../app/config').getConfiguration();

const appRoot = `${process.cwd()}/`;
const configsDir = path.join(appRoot, 'app', 'configurations');
const configFiles = fs.readdirSync(configsDir);

/* ********* Global ********* */
const port = config.PORT || 8080;
const app = express();
Expand Down Expand Up @@ -295,6 +300,63 @@ function setUpAvailableTickets() {
});
}

function getZoneUrl(json) {
const zoneLayer = json.layers.find(
layer => layer.name.fi === 'Vyöhykkeet' || layer.name.en === 'Zones',
);
if (zoneLayer && !config.zoneGeoJson) {
// use a geoJson source to initialize combined zone data
config.zoneGeoJson = { layers: [zoneLayer] };
}
return zoneLayer?.url;
}

async function fetchGeoJsonConfig(url) {
const response = await getJson(url);
return response.geoJson || response.geojson;
}

function collectGeoJsonZones() {
if (!process.env.ASSEMBLE_GEOJSON) {
return Promise.resolve();
}
return new Promise(mainResolve => {
const promises = [];
configFiles.forEach(file => {
if (file.startsWith('config')) {
// eslint-disable-next-line global-require,import/no-dynamic-require
const conf = require(`${configsDir}/${file}`);
const { geoJson } = conf.default;
if (geoJson) {
if (geoJson.layerConfigUrl) {
promises.push(
new Promise(resolve => {
fetchGeoJsonConfig(geoJson.layerConfigUrl).then(data => {
resolve(getZoneUrl(data));
});
}),
);
} else {
promises.push(
new Promise(resolve => {
resolve(getZoneUrl(geoJson));
}),
);
}
}
}
});

Promise.all(promises).then(urls => {
if (config.zoneGeoJson) {
// valid zone data was found
config.zoneGeoJson.layers[0].url = urls.filter(url => !!url); // drop invalid
}
mainResolve();
});
});
}

function startServer() {
const server = app.listen(port, () =>
console.log('Digitransit-ui available on port %d', server.address().port),
Expand All @@ -310,8 +372,10 @@ setUpStaticFolders();
setUpMiddleware();
setUpRoutes();
setUpErrorHandling();
Promise.all([setUpAvailableRouteTimetables(), setUpAvailableTickets()]).then(
() => startServer(),
);
Promise.all([
setUpAvailableRouteTimetables(),
setUpAvailableTickets(),
collectGeoJsonZones(),
]).then(() => startServer());

module.exports.app = app;
Loading