Windshaft-cartodb/lib/models/mapconfig/adapter/vector-mapconfig-adapter.js

66 lines
2.2 KiB
JavaScript
Raw Normal View History

'use strict';
const queryUtils = require('../../../utils/query-utils');
2018-06-01 18:18:07 +08:00
const dateWrapper = require('../../../utils/date-wrapper');
2018-06-01 18:18:07 +08:00
/**
* This middleware wraps the layer query transforming the date fields into numbers because mvt tiles
* doesnt support dates as primitive type.
2018-06-12 01:31:42 +08:00
*
2018-06-01 18:18:07 +08:00
* - This middleware is ONLY activated when the `dates_as_numbers` option is enabled for some layer in the mapConfig.
*/
class VectorMapConfigAdapter {
constructor(pgConnection) {
this.pgConnection = pgConnection;
}
getMapConfig(user, requestMapConfig, params, context, callback) {
2018-06-01 18:18:07 +08:00
if (!this._isDatesAsNumbersFlagEnabled(requestMapConfig)) {
return callback(null, requestMapConfig);
}
this._wrapDates(requestMapConfig, user)
.then(updatedRequestMapConfig => callback(null, updatedRequestMapConfig))
.catch(callback);
}
_wrapDates(requestMapConfig, user) {
2018-06-05 15:34:44 +08:00
return Promise.all(requestMapConfig.layers.map(layer => this._wrapLayer(layer, user)))
.then(() => requestMapConfig);
}
_wrapLayer(layer, user) {
if (!layer.options.dates_as_numbers || !layer.options.sql) {
2018-06-12 01:31:42 +08:00
return Promise.resolve(layer);
}
2018-06-05 15:34:44 +08:00
const originalQuery = layer.options.sql;
return this._getColumns(user, originalQuery)
.then(result => {
2018-06-01 00:53:01 +08:00
const newSqlQuery = dateWrapper.wrapDates(originalQuery, result.fields);
2018-06-05 15:34:44 +08:00
layer.options.sql = newSqlQuery;
return layer;
});
}
_getColumns(user, originalQuery) {
return new Promise((resolve, reject) => {
this.pgConnection.getConnection(user, (err, connection) => {
if (err) {
return reject(err);
}
const query = queryUtils.getQueryLimited(queryUtils.substituteDummyTokens(originalQuery), 0);
queryUtils.queryPromise(connection, query)
.then(resolve)
.catch(reject);
});
});
}
2018-06-01 18:18:07 +08:00
_isDatesAsNumbersFlagEnabled(requestMapConfig) {
2018-06-01 18:25:36 +08:00
return requestMapConfig.layers && requestMapConfig.layers.some(layer => layer.options.dates_as_numbers);
2018-06-01 18:18:07 +08:00
}
}
module.exports = VectorMapConfigAdapter;