Apply automatic eslint fixes

This commit is contained in:
Daniel García Aubert
2019-10-21 19:07:24 +02:00
parent 593d9e40f6
commit 4d70ac0894
246 changed files with 11782 additions and 11454 deletions

21
app.js
View File

@@ -76,7 +76,6 @@ var agentOptions = _.defaults(global.environment.httpAgent || {}, {
http.globalAgent = new http.Agent(agentOptions);
https.globalAgent = new https.Agent(agentOptions);
global.log4js = require('log4js');
var log4jsConfig = {
appenders: [],
@@ -87,16 +86,16 @@ if ( global.environment.log_filename ) {
var logFilename = path.resolve(global.environment.log_filename);
var logDirectory = path.dirname(logFilename);
if (!fs.existsSync(logDirectory)) {
logError("Log filename directory does not exist: " + logDirectory);
logError('Log filename directory does not exist: ' + logDirectory);
process.exit(1);
}
log("Logs will be written to " + logFilename);
log('Logs will be written to ' + logFilename);
log4jsConfig.appenders.push(
{ type: "file", absolute: true, filename: logFilename }
{ type: 'file', absolute: true, filename: logFilename }
);
} else {
log4jsConfig.appenders.push(
{ type: "console", layout: { type:'basic' } }
{ type: 'console', layout: { type: 'basic' } }
);
}
@@ -118,13 +117,13 @@ var backlog = global.environment.maxConnections || 128;
var listener = server.listen(serverOptions.bind.port, serverOptions.bind.host, backlog);
var version = require("./package").version;
var version = require('./package').version;
listener.on('listening', function () {
log("Using Node.js %s", process.version);
log('Using Node.js %s', process.version);
log('Using configuration file "%s"', configurationFile);
log(
"Windshaft tileserver %s started on %s:%s PID=%d (%s)",
'Windshaft tileserver %s started on %s:%s PID=%d (%s)',
version, serverOptions.bind.host, serverOptions.bind.port, process.pid, ENVIRONMENT
);
});
@@ -179,9 +178,9 @@ process.on('SIGHUP', function() {
});
if (global.gc) {
var gcInterval = Number.isFinite(global.environment.gc_interval) ?
global.environment.gc_interval :
10000;
var gcInterval = Number.isFinite(global.environment.gc_interval)
? global.environment.gc_interval
: 10000;
if (gcInterval > 0) {
setInterval(function gcForcedCycle () {

View File

@@ -232,7 +232,6 @@ module.exports = class ApiRouter {
}
};
function createTemplateMaps ({ redisPool, surrogateKeysCache }) {
const templateMaps = new TemplateMaps(redisPool, {
max_user_templates: global.environment.maxUserTemplates
@@ -245,7 +244,7 @@ function createTemplateMaps ({ redisPool, surrogateKeysCache }) {
username: owner,
type: 'named_map_invalidation',
elapsed: Date.now() - startTime,
error: !!err ? JSON.stringify(err.message) : undefined
error: err ? JSON.stringify(err.message) : undefined
});
if (err) {
global.logger.warn(logMessage);
@@ -255,7 +254,6 @@ function createTemplateMaps ({ redisPool, surrogateKeysCache }) {
});
}
['update', 'delete'].forEach(function (eventType) {
templateMaps.on(eventType, invalidateNamedMap);
});
@@ -289,7 +287,6 @@ function createRendererFactory ({ redisPool, serverOptions, environmentOptions }
var onTileErrorStrategy;
if (environmentOptions.enabledFeatures.onTileErrorStrategy !== false) {
onTileErrorStrategy = function onTileErrorStrategy$TimeoutTile (err, tile, headers, stats, format, callback) {
function isRenderTimeoutError (err) {
return err.message === 'Render timed out';
}
@@ -308,7 +305,7 @@ function createRendererFactory ({ redisPool, serverOptions, environmentOptions }
if (isTimeoutError(err) && isRasterFormat(format)) {
return callback(null, timeoutErrorTile, {
'Content-Type': 'image/png',
'Content-Type': 'image/png'
}, {});
} else {
return callback(err, tile, headers, stats);

View File

@@ -93,11 +93,11 @@ function prepareResponse () {
return analysisB.table.size - analysisA.table.size;
}
if (!!analysisA.table) {
if (analysisA.table) {
return -1;
}
if (!!analysisB.table) {
if (analysisB.table) {
return 1;
}

View File

@@ -164,7 +164,6 @@ function prepareAdapterMapConfig (mapConfigAdapter) {
stats.mapType = 'anonymous';
req.profiler.add(stats);
if (err) {
return next(err);
}
@@ -186,8 +185,13 @@ function createLayergroup (mapBackend, userLimitsBackend, pgConnection, affected
const { dbuser, dbname, dbpassword, dbhost, dbport } = res.locals;
const params = {
cache_buster, api_key,
dbuser, dbname, dbpassword, dbhost, dbport
cache_buster,
api_key,
dbuser,
dbname,
dbpassword,
dbhost,
dbport
};
const datasource = context.datasource || Datasource.EmptyDatasource();

View File

@@ -70,8 +70,13 @@ function getFeatureAttributes (attributesBackend) {
const params = {
token,
dbuser, dbname, dbpassword, dbhost, dbport,
layer, fid
dbuser,
dbname,
dbpassword,
dbhost,
dbport,
layer,
fid
};
attributesBackend.getFeatureAttributes(mapConfigProvider, params, false, (err, tile, stats = {}) => {

View File

@@ -71,9 +71,16 @@ function getClusteredFeatures (clusterBackend) {
const { aggregation } = req.query;
const params = {
user, token,
dbuser, dbname, dbpassword, dbhost, dbport,
layer, zoom, clusterId,
user,
token,
dbuser,
dbname,
dbpassword,
dbhost,
dbport,
layer,
zoom,
clusterId,
aggregation
};

View File

@@ -25,7 +25,7 @@ const ALLOWED_DATAVIEW_QUERY_PARAMS = [
'aggregation', // string
'offset', // number
'q', // widgets search
'categories', // number
'categories' // number
];
module.exports = class DataviewLayergroupController {

View File

@@ -60,7 +60,8 @@ module.exports = class PreviewTemplateController {
checkStaticImageFormat(),
namedMapProvider({
namedMapProviderCache: this.namedMapProviderCache,
label: 'STATIC_VIZ_MAP', forcedFormat: 'png'
label: 'STATIC_VIZ_MAP',
forcedFormat: 'png'
}),
getTemplate({ label: 'STATIC_VIZ_MAP' }),
prepareLayerFilterFromPreviewLayers({
@@ -123,9 +124,17 @@ function prepareLayerFilterFromPreviewLayers ({ namedMapProviderCache, label })
const { template_id, format } = req.params;
const params = {
user, token, cache_buster, api_key,
dbuser, dbname, dbpassword, dbhost, dbport,
template_id, format
user,
token,
cache_buster,
api_key,
dbuser,
dbname,
dbpassword,
dbhost,
dbport,
template_id,
format
};
// overwrites 'all' default filter

View File

@@ -51,8 +51,8 @@ module.exports = class TileLayergroupController {
// that performs only the middlewares of the first path that matches
// for that we use one array to group all paths.
mapRouter.get([
`/:token/:z/:x/:y@:scale_factor?x.:format`, // 1
`/:token/:z/:x/:y.:format`, // 2
'/:token/:z/:x/:y@:scale_factor?x.:format', // 1
'/:token/:z/:x/:y.:format', // 2
`/:token${not('static')}/:layer/:z/:x/:y.(:format)`
], this.middlewares());
}
@@ -149,7 +149,6 @@ function incrementErrorMetrics (statsClient) {
function tileError () {
return function tileErrorMiddleware (err, req, res, next) {
// See https://github.com/Vizzuality/Windshaft-cartodb/issues/68
let errMsg = err.message ? ('' + err.message) : ('' + err);

View File

@@ -10,7 +10,7 @@ module.exports = function authorize (authBackend) {
}
if (!authorized) {
err = new Error("Sorry, you are unauthorized (permission denied)");
err = new Error('Sorry, you are unauthorized (permission denied)');
err.http_status = 403;
return next(err);
}

View File

@@ -13,8 +13,8 @@ module.exports = function cors () {
headers.push('Content-Type');
}
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Headers", headers.join(', '));
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Headers', headers.join(', '));
next();
};

View File

@@ -17,10 +17,10 @@ module.exports = function credentials () {
function getApikeyCredentialsFromRequest (req) {
let apikeyCredentials = {
token: null,
username: null,
username: null
};
for (let getter of apikeyGetters) {
for (const getter of apikeyGetters) {
apikeyCredentials = getter(req);
if (apikeyTokenFound(apikeyCredentials)) {
break;
@@ -33,7 +33,7 @@ function getApikeyCredentialsFromRequest(req) {
const apikeyGetters = [
getApikeyTokenFromHeaderAuthorization,
getApikeyTokenFromRequestQueryString,
getApikeyTokenFromRequestBody,
getApikeyTokenFromRequestBody
];
function getApikeyTokenFromHeaderAuthorization (req) {
@@ -47,7 +47,7 @@ function getApikeyTokenFromHeaderAuthorization(req) {
} else {
return {
username: null,
token: null,
token: null
};
}
}
@@ -63,7 +63,7 @@ function getApikeyTokenFromRequestQueryString(req) {
return {
username: null,
token: token,
token: token
};
}
@@ -78,7 +78,7 @@ function getApikeyTokenFromRequestBody(req) {
return {
username: null,
token: token,
token: token
};
}

View File

@@ -10,7 +10,7 @@ module.exports = function dbConnSetup (pgConnection) {
req.profiler.done('dbConnSetup');
if (err) {
if (err.message && -1 !== err.message.indexOf('name not found')) {
if (err.message && err.message.indexOf('name not found') !== -1) {
err.http_status = 404;
}

View File

@@ -55,7 +55,7 @@ function isTimeoutError (errorTypes) {
function getErrorTypes (error) {
return {
renderTimeoutError: isRenderTimeoutError(error),
datasourceTimeoutError: isDatasourceTimeoutError(error),
datasourceTimeoutError: isDatasourceTimeoutError(error)
};
}
@@ -115,17 +115,14 @@ function statusFromErrorMessage(errMsg) {
// Find an appropriate statusCode based on message
// jshint maxcomplexity:7
var statusCode = 400;
if ( -1 !== errMsg.indexOf('permission denied') ) {
if (errMsg.indexOf('permission denied') !== -1) {
statusCode = 403;
}
else if ( -1 !== errMsg.indexOf('authentication failed') ) {
} else if (errMsg.indexOf('authentication failed') !== -1) {
statusCode = 403;
}
else if (errMsg.match(/Postgis Plugin.*[\s|\n].*column.*does not exist/)) {
} else if (errMsg.match(/Postgis Plugin.*[\s|\n].*column.*does not exist/)) {
statusCode = 400;
}
else if ( -1 !== errMsg.indexOf('does not exist') ) {
if ( -1 !== errMsg.indexOf(' role ') ) {
} else if (errMsg.indexOf('does not exist') !== -1) {
if (errMsg.indexOf(' role ') !== -1) {
statusCode = 403; // role 'xxx' does not exist
} else if (errMsg.match(/function .* does not exist/)) {
statusCode = 400; // invalid SQL (SQL function does not exist)
@@ -134,7 +131,6 @@ function statusFromErrorMessage(errMsg) {
}
}
return statusCode;
}
@@ -174,7 +170,7 @@ function errorMessageWithContext(err) {
var error = {
type: err.type || 'unknown',
message: stripConnectionInfo(message),
message: stripConnectionInfo(message)
};
for (var prop in err) {
@@ -188,10 +184,10 @@ function errorMessageWithContext(err) {
}
function setErrorHeader (errors, statusCode, res) {
let errorsCopy = errors.slice(0);
const errorsCopy = errors.slice(0);
const mainError = errorsCopy.shift();
let errorsLog = {
const errorsLog = {
mainError: {
statusCode: statusCode || 200,
message: mainError.message,
@@ -228,7 +224,7 @@ function stringifyForLogs(object) {
} else if (typeof object[key] === 'object') {
stringifyForLogs(object[key]);
} else if (object[key] instanceof Array) {
for (let element of object[key]) {
for (const element of object[key]) {
stringifyForLogs(element);
}
}

View File

@@ -10,9 +10,9 @@ module.exports = function setLastModifiedHeader () {
if (cache_buster) {
const cacheBuster = parseInt(cache_buster, 10);
const lastModifiedDate = Number.isFinite(cacheBuster) && cacheBuster !== 0 ?
new Date(cacheBuster) :
new Date();
const lastModifiedDate = Number.isFinite(cacheBuster) && cacheBuster !== 0
? new Date(cacheBuster)
: new Date();
res.set('Last-Modified', lastModifiedDate.toUTCString());

View File

@@ -16,9 +16,21 @@ module.exports = function createMapStoreMapConfigProvider (
const { layer: layerFromQuery } = req.query;
const params = {
user, token, cache_buster, api_key,
dbuser, dbname, dbpassword, dbhost, dbport,
layer: (layerFromQuery || layerFromParams), z, x, y, scale_factor, format
user,
token,
cache_buster,
api_key,
dbuser,
dbname,
dbpassword,
dbhost,
dbport,
layer: (layerFromQuery || layerFromParams),
z,
x,
y,
scale_factor,
format
};
if (forcedFormat) {

View File

@@ -8,9 +8,21 @@ module.exports = function getNamedMapProvider ({ namedMapProviderCache, label, f
const { layer: layerFromQuery } = req.query;
const params = {
user, token, cache_buster, api_key,
dbuser, dbname, dbpassword, dbhost, dbport,
template_id, layer: (layerFromQuery || layerFromParams), z, x, y, format
user,
token,
cache_buster,
api_key,
dbuser,
dbname,
dbpassword,
dbhost,
dbport,
template_id,
layer: (layerFromQuery || layerFromParams),
z,
x,
y,
format
};
if (forcedFormat) {

View File

@@ -46,7 +46,7 @@ function rateLimit(userLimitsBackend, endpointGroup = null) {
// retry is floor rounded in seconds by redis-cell
res.set('Retry-After', retry + 1);
let rateLimitError = new Error(
const rateLimitError = new Error(
'You are over platform\'s limits: too many requests.' +
' Please contact us to know more details'
);
@@ -61,7 +61,6 @@ function rateLimit(userLimitsBackend, endpointGroup = null) {
};
}
function isRateLimitEnabled (endpointGroup) {
return global.environment.enabledFeatures.rateLimitsEnabled &&
endpointGroup &&

View File

@@ -20,7 +20,7 @@ module.exports = function stats (options) {
// May throw due to dns, see: http://github.com/CartoDB/Windshaft/issues/166
req.profiler.sendStats();
} catch (err) {
debug("error sending profiling stats: " + err);
debug('error sending profiling stats: ' + err);
}
});

View File

@@ -6,7 +6,6 @@ const timeoutErrorVectorTile = fs.readFileSync(__dirname + '/../../../assets/ren
module.exports = function vectorError () {
return function vectorErrorMiddleware (err, req, res, next) {
if (req.params.format === 'mvt') {
if (isTimeoutError(err) || isRateLimitError(err)) {
res.set('Content-Type', 'application/x-protobuf');
return res.status(429).send(timeoutErrorVectorTile);
@@ -17,7 +16,6 @@ module.exports = function vectorError() {
};
};
function isRenderTimeoutError (err) {
return err.message === 'Render timed out';
}

View File

@@ -19,7 +19,7 @@ module.exports = class AdminTemplateController {
}
route (templateRouter) {
templateRouter.options(`/:template_id`);
templateRouter.options('/:template_id');
templateRouter.post('/', this.middlewares({
action: 'create',

View File

@@ -21,7 +21,7 @@ module.exports = class TemplateRouter {
authBackend,
layergroupMetadata,
namedMapProviderCache,
tileBackend,
tileBackend
} = collaborators;
this.namedMapController = new NamedMapController(

View File

@@ -109,7 +109,7 @@ AuthBackend.prototype.authorizedByAPIKey = function(user, res, callback) {
};
function isNameNotFoundError (err) {
return err.message && -1 !== err.message.indexOf('name not found');
return err.message && err.message.indexOf('name not found') !== -1;
}
function usernameMatches (basicAuthUsername, requestUsername) {

View File

@@ -71,8 +71,8 @@ function getFeatures (pg, layer, params, callback) {
}
const SKIP_COLUMNS = {
'the_geom': true,
'the_geom_webmercator': true
the_geom: true,
the_geom_webmercator: true
};
function getColumnsName (pg, query, callback) {
@@ -194,9 +194,8 @@ function parseAggregation (aggregation) {
try {
aggregation = JSON.parse(aggregation);
} catch (err) {
throw new Error(`Invalid aggregation input, should be a a valid JSON`);
throw new Error('Invalid aggregation input, should be a a valid JSON');
}
}
return aggregation;
@@ -207,7 +206,7 @@ function validateAggregation (aggregation) {
const { columns, expressions } = aggregation;
if (!hasColumns(columns)) {
throw new Error(`Invalid aggregation input, columns should be and array of column names`);
throw new Error('Invalid aggregation input, columns should be and array of column names');
}
validateExpressions(expressions);
@@ -221,16 +220,16 @@ function hasColumns (columns) {
function validateExpressions (expressions) {
if (expressions !== undefined) {
if (!isValidExpression(expressions)) {
throw new Error(`Invalid aggregation input, expressions should be and object with valid functions`);
throw new Error('Invalid aggregation input, expressions should be and object with valid functions');
}
for (const { aggregate_function, aggregated_column } of Object.values(expressions)) {
if (typeof aggregated_column !== 'string') {
throw new Error(`Invalid aggregation input, aggregated column should be an string`);
throw new Error('Invalid aggregation input, aggregated column should be an string');
}
if (typeof aggregate_function !== 'string') {
throw new Error(`Invalid aggregation input, aggregate function should be an string`);
throw new Error('Invalid aggregation input, aggregate function should be an string');
}
}
}

View File

@@ -10,7 +10,7 @@ function FilterStatsBackends(pgQueryRunner) {
module.exports = FilterStatsBackends;
function getEstimatedRows (pgQueryRunner, username, query, callback) {
pgQueryRunner.run(username, "EXPLAIN (FORMAT JSON)"+query, function(err, result_rows) {
pgQueryRunner.run(username, 'EXPLAIN (FORMAT JSON)' + query, function (err, result_rows) {
if (err) {
callback(err);
return;

View File

@@ -41,7 +41,6 @@ LayerStats.prototype.getStats = function (mapConfig, dbConnection, callback) {
return callback(err, stats);
});
};
module.exports = LayerStats;

View File

@@ -32,8 +32,7 @@ function _getSQL(ctx, query, type='pre', zoom=0) {
let sql;
if (type === 'pre') {
sql = ctx.preQuery;
}
else {
} else {
sql = ctx.aggrQuery;
}
sql = queryUtils.substituteTokensForZoom(sql, zoom || 0);
@@ -114,7 +113,7 @@ function mergeColumns(results) {
return {};
}
return results.reduce((a, b) => {
let c = Object.assign({}, b || {}, a || {});
const c = Object.assign({}, b || {}, a || {});
Object.keys(c).forEach(key => {
if (b.hasOwnProperty(key)) {
c[key] = Object.assign(c[key], b[key]);
@@ -176,7 +175,7 @@ function _columnStats(ctx, columns, dimensions) {
return Promise.resolve();
}
if (_columnsMetadataRequired(ctx.metaOptions)) {
let queries = [];
const queries = [];
let aggr = [];
if (ctx.metaOptions.columnStats) {
queries.push(new Promise(resolve => resolve({ columns }))); // add columns as first result
@@ -187,9 +186,9 @@ function _columnStats(ctx, columns, dimensions) {
);
if (columns[name].type === 'string') {
const topN = ctx.metaOptions.columnStats.topCategories || 1024;
const includeNulls = ctx.metaOptions.columnStats.hasOwnProperty('includeNulls') ?
ctx.metaOptions.columnStats.includeNulls :
true;
const includeNulls = ctx.metaOptions.columnStats.hasOwnProperty('includeNulls')
? ctx.metaOptions.columnStats.includeNulls
: true;
// TODO: ctx.metaOptions.columnStats.maxCategories
// => use PG stats to dismiss columns with more distinct values
@@ -223,7 +222,7 @@ function _columnStats(ctx, columns, dimensions) {
ctx.dbConnection,
_getSQL(ctx, sql => `SELECT ${aggr.join(',')} FROM (${sql}) AS __cdb_query`)
).then(res => {
let stats = { columns: {}, dimensions: {} };
const stats = { columns: {}, dimensions: {} };
Object.keys(columns).forEach(name => {
stats.columns[name] = {};
columnAggregations(columns[name]).forEach(fn => {
@@ -284,8 +283,8 @@ function fieldTypeSafe(dbConnection, field) {
// columns are returned as an object { columnName1: { type1: ...}, ..}
// for consistency with SQL API
function formatResultFields (dbConnection, fields = []) {
let nfields = {};
for (let field of fields) {
const nfields = {};
for (const field of fields) {
nfields[field.name] = { type: fieldTypeSafe(dbConnection, field) };
}
return nfields;
@@ -293,14 +292,14 @@ function formatResultFields(dbConnection, fields = []) {
MapnikLayerStats.prototype.getStats =
function (layer, dbConnection, callback) {
let aggrQuery = layer.options.sql;
let preQuery = layer.options.sql_raw || aggrQuery;
const aggrQuery = layer.options.sql;
const preQuery = layer.options.sql_raw || aggrQuery;
let ctx = {
const ctx = {
dbConnection,
preQuery,
aggrQuery,
metaOptions: layer.options.metadata || {},
metaOptions: layer.options.metadata || {}
};
// TODO: could save some queries if queryUtils.getAggregationMetadata() has been used and kept somewhere

View File

@@ -10,7 +10,6 @@ function PgConnection(metadataBackend) {
module.exports = PgConnection;
// Set db authentication parameters to those of the given username
//
// @param username the cartodb username, mapped to a database username
@@ -70,10 +69,9 @@ PgConnection.prototype.setDBAuth = function(username, params, apikeyType, callba
};
function isNameNotFoundError (err) {
return err.message && -1 !== err.message.indexOf('name not found');
return err.message && err.message.indexOf('name not found') !== -1;
}
// Set db connection parameters to those for the given username
//
// @param dbowner cartodb username of database owner,
@@ -118,7 +116,7 @@ PgConnection.prototype.setDBConn = function(dbowner, params, callback) {
*/
PgConnection.prototype.getConnection = function (username, callback) {
debug("getConn1");
debug('getConn1');
this.getDatabaseParams(username, (err, databaseParams) => {
if (err) {
@@ -131,7 +129,6 @@ PgConnection.prototype.getConnection = function(username, callback) {
port: databaseParams.dbport,
dbname: databaseParams.dbname
}));
});
};

View File

@@ -16,7 +16,6 @@ module.exports = PgQueryRunner;
* @param {Function} callback function({Error}, {Array}) second argument is guaranteed to be an array
*/
PgQueryRunner.prototype.run = function (username, query, callback) {
this.pgConnection.getDatabaseParams(username, (err, databaseParams) => {
if (err) {
return callback(err);

View File

@@ -21,16 +21,16 @@ TablesExtentBackend.prototype.getBounds = function (username, tables, callback)
});
var query = [
"WITH ext as (" +
"SELECT ST_Transform(ST_SetSRID(ST_Extent(ST_Union(ARRAY[",
'WITH ext as (' +
'SELECT ST_Transform(ST_SetSRID(ST_Extent(ST_Union(ARRAY[',
estimatedExtentSQLs.join(','),
"])), 3857), 4326) geom)",
"SELECT",
"ST_XMin(geom) west,",
"ST_YMin(geom) south,",
"ST_XMax(geom) east,",
"ST_YMax(geom) north",
"FROM ext"
'])), 3857), 4326) geom)',
'SELECT',
'ST_XMin(geom) west,',
'ST_YMin(geom) south,',
'ST_XMax(geom) east,',
'ST_YMax(geom) north',
'FROM ext'
].join(' ');
this.pgQueryRunner.run(username, query, function handleBoundsResult (err, rows) {

View File

@@ -5,11 +5,9 @@ var debug = require('debug')('windshaft:templates');
var _ = require('underscore');
var dot = require('dot');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
// Class handling map templates
//
// See http://github.com/CartoDB/Windshaft-cartodb/wiki/Template-maps
@@ -47,14 +45,13 @@ function TemplateMaps(redis_pool, opts) {
// 1. User templates: set of per-user map templates
// User templates (HASH:tpl_id->tpl_val)
this.key_usr_tpl = dot.template("map_tpl|{{=it.owner}}");
this.key_usr_tpl = dot.template('map_tpl|{{=it.owner}}');
}
util.inherits(TemplateMaps, EventEmitter);
module.exports = TemplateMaps;
// --------------- PRIVATE METHODS --------------------------------
TemplateMaps.prototype._userTemplateLimit = function () {
@@ -89,11 +86,11 @@ var _reValidPlaceholderIdentifier = /^[a-z][0-9a-z_]*$/i;
// jshint maxcomplexity:15
TemplateMaps.prototype._checkInvalidTemplate = function (template) {
if (template.version !== '0.0.1') {
return new Error("Unsupported template version " + template.version);
return new Error('Unsupported template version ' + template.version);
}
var tplname = template.name;
if (!tplname) {
return new Error("Missing template name");
return new Error('Missing template name');
}
if (!tplname.match(_reValidNameIdentifier)) {
return new Error("Invalid characters in template name '" + tplname + "'");
@@ -135,7 +132,7 @@ TemplateMaps.prototype._checkInvalidTemplate = function(template) {
}
break;
default:
return new Error("Unsupported authentication method: " + auth.method);
return new Error('Unsupported authentication method: ' + auth.method);
}
return false;
@@ -432,14 +429,14 @@ TemplateMaps.prototype.isAuthorized = function(template, authTokens) {
//
// @throws Error on malformed template or parameter
//
var _reNumber = /^([-+]?[\d\.]?\d+([eE][+-]?\d+)?)$/,
_reCSSColorName = /^[a-zA-Z]+$/,
_reCSSColorVal = /^#[0-9a-fA-F]{3,6}$/;
var _reNumber = /^([-+]?[\d\.]?\d+([eE][+-]?\d+)?)$/;
var _reCSSColorName = /^[a-zA-Z]+$/;
var _reCSSColorVal = /^#[0-9a-fA-F]{3,6}$/;
function _replaceVars (str, params) {
// Construct regular expressions for each param
Object.keys(params).forEach(function (k) {
str = str.replace(new RegExp("<%=\\s*" + k + "\\s*%>", "g"), params[k]);
str = str.replace(new RegExp('<%=\\s*' + k + '\\s*%>', 'g'), params[k]);
});
return str;
}
@@ -458,25 +455,21 @@ TemplateMaps.prototype.instance = function(template, params) {
if (type === 'sql_literal') {
// duplicate any single-quote
val = val.replace(/'/g, "''");
}
else if ( type === 'sql_ident' ) {
} else if (type === 'sql_ident') {
// duplicate any double-quote
val = val.replace(/"/g, '""');
}
else if ( type === 'number' ) {
} else if (type === 'number') {
// check it's a number
if (typeof (val) !== 'number' && !val.match(_reNumber)) {
throw new Error("Invalid number value for template parameter '" + k + "': " + val);
}
}
else if ( type === 'css_color' ) {
} else if (type === 'css_color') {
// check it only contains letters or
// starts with # and only contains hexdigits
if (!val.match(_reCSSColorName) && !val.match(_reCSSColorVal)) {
throw new Error("Invalid css_color value for template parameter '" + k + "': " + val);
}
}
else {
} else {
// NOTE: should be checked at template create/update time
throw new Error("Invalid placeholder type '" + type + "'");
}

View File

@@ -10,7 +10,6 @@ function NamedMaps(owner, name) {
module.exports = NamedMaps;
NamedMaps.prototype.key = function () {
return this.namespace + ':' + shortHashKey(this.owner + ':' + this.name);
};

View File

@@ -12,7 +12,6 @@ function SurrogateKeysCache(cacheBackends) {
module.exports = SurrogateKeysCache;
/**
* @param response should respond to `header(key, value)` method
* @param cacheObject should respond to `key() -> String` method
@@ -23,11 +22,10 @@ SurrogateKeysCache.prototype.tag = function(response, cacheObject) {
response.get('Surrogate-Key'),
Array.isArray(newKey) ? cacheObject.key().join(' ') : newKey
));
};
function appendSurrogateKey (currentKey, newKey) {
if (!!currentKey) {
if (currentKey) {
newKey = currentKey + ' ' + newKey;
}
return newKey;

View File

@@ -108,7 +108,7 @@ module.exports = class AggregationMapConfig extends MapConfig {
}
isAggregationLayer (index) {
let hasAggregation = this.hasLayerAggregation(index);
const hasAggregation = this.hasLayerAggregation(index);
// for vector-only MapConfig are aggregated unless explicitly disabled
return hasAggregation || (
this.isVectorOnlyMapConfig() && hasAggregation !== AggregationMapConfig.HAS_AGGREGATION_DISABLED
@@ -176,7 +176,7 @@ module.exports = class AggregationMapConfig extends MapConfig {
_getLayerAggregationRequiredColumns (index) {
const { columns, dimensions } = this.getAggregation(index);
let finalColumns = ['cartodb_id', '_cdb_feature_count'];
const finalColumns = ['cartodb_id', '_cdb_feature_count'];
let aggregatedColumns = [];
if (columns) {
@@ -192,9 +192,9 @@ module.exports = class AggregationMapConfig extends MapConfig {
}
doesLayerReachThreshold (index, featureCount) {
const threshold = this.getAggregation(index) && this.getAggregation(index).threshold ?
this.getAggregation(index).threshold :
AggregationMapConfig.THRESHOLD;
const threshold = this.getAggregation(index) && this.getAggregation(index).threshold
? this.getAggregation(index).threshold
: AggregationMapConfig.THRESHOLD;
return featureCount >= threshold;
}

View File

@@ -50,22 +50,22 @@ module.exports.infoForOptions = (options) => {
};
const SUPPORTED_AGGREGATE_FUNCTIONS = {
'count': {
count: {
sql: (column_name, params) => `count(${params.aggregated_column || '*'})`
},
'avg': {
avg: {
sql: (column_name, params) => `avg(${params.aggregated_column || column_name})`
},
'sum': {
sum: {
sql: (column_name, params) => `sum(${params.aggregated_column || column_name})`
},
'min': {
min: {
sql: (column_name, params) => `min(${params.aggregated_column || column_name})`
},
'max': {
max: {
sql: (column_name, params) => `max(${params.aggregated_column || column_name})`
},
'mode': {
mode: {
sql: (column_name, params) => `mode() WITHIN GROUP (ORDER BY ${params.aggregated_column || column_name})`
}
};
@@ -73,7 +73,7 @@ const SUPPORTED_AGGREGATE_FUNCTIONS = {
module.exports.SUPPORTED_AGGREGATE_FUNCTIONS = Object.keys(SUPPORTED_AGGREGATE_FUNCTIONS);
const sep = (list) => {
let expr = list.join(', ');
const expr = list.join(', ');
return expr ? ', ' + expr : expr;
};
@@ -95,7 +95,7 @@ const aggregateExpression = (column_name, column_parameters) => {
};
const aggregateColumnDefs = ctx => {
let columns = aggregateColumns(ctx);
const columns = aggregateColumns(ctx);
return sep(Object.keys(columns).map(column_name => {
const aggregate_expression = aggregateExpression(column_name, columns[column_name]);
return `${aggregate_expression} AS ${column_name}`;
@@ -135,7 +135,7 @@ const dimensionExpression = definition => {
};
const dimensionNamesAndExpressions = (ctx) => {
let dimensions = aggregateDimensions(ctx);
const dimensions = aggregateDimensions(ctx);
return Object.keys(dimensions).map(dimensionName => {
const dimension = adaptDimensionDefinition(dimensions[dimensionName]);
const expression = dimensionExpression(dimension);
@@ -192,7 +192,7 @@ const sqlQ = (value) => {
const FILTERS = {
between: (expr, filter) => {
const lo = filter.greater_than_or_equal_to, hi = filter.less_than_or_equal_to;
const lo = filter.greater_than_or_equal_to; const hi = filter.less_than_or_equal_to;
if (lo != null && hi != null) {
return `(${expr} BETWEEN ${sqlQ(lo)} AND ${sqlQ(hi)})`;
}
@@ -218,7 +218,7 @@ const FILTERS = {
}
},
range: (expr, filter) => {
let conds = [];
const conds = [];
if (filter.greater_than_or_equal_to != null) {
conds.push(`(${expr} >= ${sqlQ(filter.greater_than_or_equal_to)})`);
}
@@ -238,15 +238,14 @@ const FILTERS = {
};
const filterConditions = ctx => {
let columns = aggregateColumns(ctx);
let dimensions = aggregateDimensions(ctx);
let filters = aggregateFilters(ctx);
const columns = aggregateColumns(ctx);
const dimensions = aggregateDimensions(ctx);
const filters = aggregateFilters(ctx);
return Object.keys(filters).map(filtered_column => {
let filtered_expr;
if (columns[filtered_column]) {
filtered_expr = aggregateExpression(filtered_column, columns[filtered_column]);
}
else if (dimensions[filtered_column]) {
} else if (dimensions[filtered_column]) {
filtered_expr = dimensions[filtered_column];
}
if (!filtered_expr) {
@@ -257,7 +256,7 @@ const filterConditions = ctx => {
};
const havingClause = ctx => {
let cond = filterConditions(ctx);
const cond = filterConditions(ctx);
return cond ? `HAVING ${cond}` : '';
};
@@ -309,18 +308,16 @@ const gridInfoQuery = ctx => {
`;
};
// Function to generate the resulting point for a cell from the aggregated data
const aggregatedPointWebMercator = (ctx) => {
switch (ctx.placement) {
// For centroid, we return the average of the cell
case 'centroid':
return ', ST_SetSRID(ST_MakePoint(AVG(cdb_x), AVG(cdb_y)), 3857) AS the_geom_webmercator';
// Middle point of the cell
case 'point-grid':
return `, ST_SetSRID(ST_MakePoint(cdb_pos_grid_x, cdb_pos_grid_y), 3857) AS the_geom_webmercator`;
return ', ST_SetSRID(ST_MakePoint(cdb_pos_grid_x, cdb_pos_grid_y), 3857) AS the_geom_webmercator';
// For point-sample we'll get a single point directly from the source
// If it's default aggregation we'll add the extra columns to keep backwards compatibility
@@ -335,7 +332,6 @@ const aggregatedPointWebMercator = (ctx) => {
// Function to generate the resulting point for a cell from the a join with the source
const aggregatedPointJoin = (ctx) => {
switch (ctx.placement) {
case 'centroid':
return '';
@@ -348,7 +344,7 @@ const aggregatedPointJoin = (ctx) => {
return `
NATURAL JOIN
(
SELECT ${ctx.isDefaultAggregation ? `*` : `cartodb_id, the_geom_webmercator`}
SELECT ${ctx.isDefaultAggregation ? '*' : 'cartodb_id, the_geom_webmercator'}
FROM
(
${ctx.sourceQuery}
@@ -368,7 +364,7 @@ NATURAL JOIN
const aggregatedPosCoordinate = (ctx, coordinate) => {
switch (ctx.placement) {
// For point-grid we return the coordinate of the middle point of the grid
case `point-grid`:
case 'point-grid':
return `(FLOOR(cdb_${coordinate} / __cdb_grid_params.cdb_res) + 0.5) * __cdb_grid_params.cdb_res`;
// For other, we return the cell position (relative to the world)
@@ -377,7 +373,6 @@ const aggregatedPosCoordinate = (ctx, coordinate) => {
}
};
const aggregationQueryTemplate = ctx => `
WITH __cdb_grid_params AS
(

View File

@@ -80,7 +80,7 @@ function createAggregationColumnNamesValidator(mapconfig) {
return function validateAggregationColumnNames (value, key, index) {
Object.keys(value).forEach((columnName) => {
if (columnName.length <= 0) {
const message = `Invalid column name, should be a non empty string`;
const message = 'Invalid column name, should be a non empty string';
throw createLayerError(message, mapconfig, index);
}
});
@@ -107,7 +107,7 @@ function createAggregatedColumnValidator (mapconfig) {
const { aggregated_column } = value[columnName];
if (typeof aggregated_column !== 'string' || aggregated_column <= 0) {
const message = `Invalid aggregated column, should be a non empty string`;
const message = 'Invalid aggregated column, should be a non empty string';
throw createLayerError(message, mapconfig, index);
}
});

View File

@@ -131,19 +131,19 @@ function serialSqlExpr(params) {
}
const isoParts = {
second: `to_char($t, 'YYYY-MM-DD"T"HH24:MI:SS')`,
minute: `to_char($t, 'YYYY-MM-DD"T"HH24:MI')`,
hour: `to_char($t, 'YYYY-MM-DD"T"HH24')`,
day: `to_char($t, 'YYYY-MM-DD')`,
month: `to_char($t, 'YYYY-MM')`,
year: `to_char($t, 'YYYY')`,
week: `to_char($t, 'IYYY-"W"IW')`,
quarter: `to_char($t, 'YYYY-"Q"Q')`,
semester: `to_char($t, 'YYYY"S"') || to_char(CEIL(date_part('month', $t)/6), '9')`,
trimester: `to_char($t, 'YYYY"t"') || to_char(CEIL(date_part('month', $t)/4), '9')`,
decade: `to_char(date_part('decade', $t), '"D"999')`,
century: `to_char($t, '"C"CC')`,
millennium: `to_char(date_part('millennium', $t), '"M"999')`
second: 'to_char($t, \'YYYY-MM-DD"T"HH24:MI:SS\')',
minute: 'to_char($t, \'YYYY-MM-DD"T"HH24:MI\')',
hour: 'to_char($t, \'YYYY-MM-DD"T"HH24\')',
day: 'to_char($t, \'YYYY-MM-DD\')',
month: 'to_char($t, \'YYYY-MM\')',
year: 'to_char($t, \'YYYY\')',
week: 'to_char($t, \'IYYY-"W"IW\')',
quarter: 'to_char($t, \'YYYY-"Q"Q\')',
semester: 'to_char($t, \'YYYY"S"\') || to_char(CEIL(date_part(\'month\', $t)/6), \'9\')',
trimester: 'to_char($t, \'YYYY"t"\') || to_char(CEIL(date_part(\'month\', $t)/4), \'9\')',
decade: 'to_char(date_part(\'decade\', $t), \'"D"999\')',
century: 'to_char($t, \'"C"CC\')',
millennium: 'to_char(date_part(\'millennium\', $t), \'"M"999\')'
};
function isoSqlExpr (params) {
@@ -156,16 +156,16 @@ function isoSqlExpr(params) {
}
const cyclicParts = {
dayOfWeek: `date_part('isodow', $t)`, // 1 = monday to 7 = sunday;
dayOfMonth: `date_part('day', $t)`, // 1 to 31
dayOfYear: `date_part('doy', $t)`, // 1 to 366
hourOfDay: `date_part('hour', $t)`, // 0 to 23
monthOfYear: `date_part('month', $t)`, // 1 to 12
quarterOfYear: `date_part('quarter', $t)`, // 1 to 4
semesterOfYear: `FLOOR((date_part('month', $t)-1)/6.0) + 1`, // 1 to 2
trimesterOfYear: `FLOOR((date_part('month', $t)-1)/4.0) + 1`, // 1 to 3
weekOfYear: `date_part('week', $t)`, // 1 to 53
minuteOfHour: `date_part('minute', $t)` // 0 to 59
dayOfWeek: 'date_part(\'isodow\', $t)', // 1 = monday to 7 = sunday;
dayOfMonth: 'date_part(\'day\', $t)', // 1 to 31
dayOfYear: 'date_part(\'doy\', $t)', // 1 to 366
hourOfDay: 'date_part(\'hour\', $t)', // 0 to 23
monthOfYear: 'date_part(\'month\', $t)', // 1 to 12
quarterOfYear: 'date_part(\'quarter\', $t)', // 1 to 4
semesterOfYear: 'FLOOR((date_part(\'month\', $t)-1)/6.0) + 1', // 1 to 2
trimesterOfYear: 'FLOOR((date_part(\'month\', $t)-1)/4.0) + 1', // 1 to 3
weekOfYear: 'date_part(\'week\', $t)', // 1 to 53
minuteOfHour: 'date_part(\'minute\', $t)' // 0 to 59
};
function cyclicSqlExpr (params) {
@@ -190,7 +190,7 @@ function validateParameters(params, checker) {
const params_errors = checker(params);
errors.push(...params_errors.errors);
if (errors.length) {
throw new Error(`Invalid time dimension:\n${errors.join("\n")}`);
throw new Error(`Invalid time dimension:\n${errors.join('\n')}`);
}
return params_errors.params;
}

View File

@@ -8,7 +8,6 @@ function CdbRequest() {
module.exports = CdbRequest;
CdbRequest.prototype.userByReq = function (req) {
var host = req.headers.host || '';
if (req.params.user) {

View File

@@ -12,8 +12,8 @@ const filteredQueryTpl = ctx => `
AND
${ctx.aggregationColumn} != '-infinity'::float
AND
${ctx.aggregationColumn} != 'NaN'::float` :
''
${ctx.aggregationColumn} != 'NaN'::float`
: ''
}
`;
@@ -30,8 +30,8 @@ const summaryQueryTpl = ctx => `
ELSE 0
END
) AS infinities_count,
sum(CASE WHEN ${ctx.aggregationColumn} = 'NaN'::float THEN 1 ELSE 0 END) AS nans_count` :
''
sum(CASE WHEN ${ctx.aggregationColumn} = 'NaN'::float THEN 1 ELSE 0 END) AS nans_count`
: ''
}
FROM (${ctx.query}) _cdb_aggregation_nulls
)
@@ -44,7 +44,7 @@ const rankedCategoriesQueryTpl = ctx => `
${ctx.aggregationFn} AS value,
row_number() OVER (ORDER BY ${ctx.aggregationFn} desc) as rank
FROM (${filteredQueryTpl(ctx)}) filtered_source
WHERE ${ctx.aggregation === "count" ? `${ctx.column}` : `${ctx.aggregationColumn}`} IS NOT NULL
WHERE ${ctx.aggregation === 'count' ? `${ctx.column}` : `${ctx.aggregationColumn}`} IS NOT NULL
GROUP BY ${ctx.column}
ORDER BY 2 DESC
)
@@ -70,7 +70,7 @@ const categoriesSummaryCountQueryTpl = ctx => `
)
`;
const specialNumericValuesColumns = () => `, nans_count, infinities_count`;
const specialNumericValuesColumns = () => ', nans_count, infinities_count';
const rankedAggregationQueryTpl = ctx => `
SELECT
@@ -138,7 +138,7 @@ const aggregationDataviewQueryTpl = ctx => `
${rankedCategoriesQueryTpl(ctx)},
${categoriesSummaryMinMaxQueryTpl(ctx)},
${categoriesSummaryCountQueryTpl(ctx)}
${!!ctx.override.ownFilter ? `${aggregationQueryTpl(ctx)}` : `${rankedAggregationQueryTpl(ctx)}`}
${ctx.override.ownFilter ? `${aggregationQueryTpl(ctx)}` : `${rankedAggregationQueryTpl(ctx)}`}
`;
const filterCategoriesQueryTpl = ctx => `
@@ -206,11 +206,11 @@ module.exports = class Aggregation extends BaseDataview {
_checkOptions (options) {
if (typeof options.column !== 'string') {
throw new Error(`Aggregation expects 'column' in dataview options`);
throw new Error('Aggregation expects \'column\' in dataview options');
}
if (typeof options.aggregation !== 'string') {
throw new Error(`Aggregation expects 'aggregation' operation in dataview options`);
throw new Error('Aggregation expects \'aggregation\' operation in dataview options');
}
if (!VALID_OPERATIONS[options.aggregation]) {
@@ -244,9 +244,9 @@ module.exports = class Aggregation extends BaseDataview {
return null;
}
const limit = Number.isFinite(override.categories) && override.categories > 0 ?
override.categories :
CATEGORIES_LIMIT;
const limit = Number.isFinite(override.categories) && override.categories > 0
? override.categories
: CATEGORIES_LIMIT;
const aggregationSql = aggregationDataviewQueryTpl({
override: override,
@@ -303,9 +303,9 @@ module.exports = class Aggregation extends BaseDataview {
search (psql, userQuery, callback) {
const escapedUserQuery = psql.escapeLiteral(`%${userQuery}%`);
const value = this.aggregation !== 'count' && this.aggregationColumn ?
`${this.aggregation}(${this.aggregationColumn})` :
'count(1)';
const value = this.aggregation !== 'count' && this.aggregationColumn
? `${this.aggregation}(${this.aggregationColumn})`
: 'count(1)';
// TODO unfiltered will be wrong as filters are already applied at this point
const query = searchQueryTpl({

View File

@@ -8,8 +8,8 @@ const formulaQueryTpl = ctx =>
`SELECT
${ctx.operation}(${utils.handleFloatColumn(ctx)}) AS result,
${utils.countNULLs(ctx)} AS nulls_count
${ctx.isFloatColumn ? `,${utils.countInfinites(ctx)} AS infinities_count,` : ``}
${ctx.isFloatColumn ? `${utils.countNaNs(ctx)} AS nans_count` : ``}
${ctx.isFloatColumn ? `,${utils.countInfinites(ctx)} AS infinities_count,` : ''}
${ctx.isFloatColumn ? `${utils.countNaNs(ctx)} AS nans_count` : ''}
FROM (${ctx.query}) __cdb_formula`;
const VALID_OPERATIONS = {
@@ -46,7 +46,7 @@ module.exports = class Formula extends BaseDataview {
_checkOptions (options) {
if (typeof options.operation !== 'string') {
throw new Error(`Formula expects 'operation' in dataview options`);
throw new Error('Formula expects \'operation\' in dataview options');
}
if (!VALID_OPERATIONS[options.operation]) {
@@ -54,11 +54,10 @@ module.exports = class Formula extends BaseDataview {
}
if (options.operation !== 'count' && typeof options.column !== 'string') {
throw new Error(`Formula expects 'column' in dataview options`);
throw new Error('Formula expects \'column\' in dataview options');
}
}
sql (psql, override, callback) {
if (!callback) {
callback = override;

View File

@@ -4,7 +4,6 @@ const BaseHistogram = require('./base-histogram');
const debug = require('debug')('windshaft:dataview:date-histogram');
const utils = require('../../../utils/query-utils');
/**
* Gets the name of a timezone with the same offset as the required
* using the pg_timezone_names table. We do this because it's simpler to pass
@@ -41,8 +40,7 @@ function dataBucketsQuery(ctx) {
if (ctx.end !== 0) {
if (condition_str === '') {
condition_str = `WHERE ${ctx.column} <= to_timestamp(${ctx.end})`;
}
else {
} else {
condition_str += ` and ${ctx.column} <= to_timestamp(${ctx.end})`;
}
}
@@ -69,20 +67,20 @@ __wd_buckets AS
* the dataBucketsQuery
*/
function allBucketsArrayQuery (ctx) {
var extra_from = ``;
var series_start = ``;
var series_end = ``;
var extra_from = '';
var series_start = '';
var series_end = '';
if (ctx.start === 0) {
extra_from = `, __wd_buckets GROUP BY __wd_tz.name`;
series_start = `min(__wd_buckets.timestamp)`;
extra_from = ', __wd_buckets GROUP BY __wd_tz.name';
series_start = 'min(__wd_buckets.timestamp)';
} else {
series_start = `date_trunc('${ctx.aggregation}', timezone(__wd_tz.name, to_timestamp(${ctx.start})))`;
}
if (ctx.end === 0) {
extra_from = `, __wd_buckets GROUP BY __wd_tz.name`;
series_end = `max(__wd_buckets.timestamp)`;
extra_from = ', __wd_buckets GROUP BY __wd_tz.name';
series_end = 'max(__wd_buckets.timestamp)';
} else {
series_end = `date_trunc('${ctx.aggregation}', timezone(__wd_tz.name, to_timestamp(${ctx.end})))`;
}
@@ -148,18 +146,18 @@ const dateIntervalQueryTpl = ctx => `
const MAX_INTERVAL_VALUE = 100;
const DATE_AGGREGATIONS = {
'auto': true,
'second' : true,
'minute': true,
'hour': true,
'day': true,
'week': true,
'month': true,
'quarter': true,
'year': true,
'decade' : true,
'century' : true,
'millennium' : true
auto: true,
second: true,
minute: true,
hour: true,
day: true,
week: true,
month: true,
quarter: true,
year: true,
decade: true,
century: true,
millennium: true
};
/**
@@ -219,8 +217,8 @@ ORDER BY bin ASC;
return null;
}
var interval = this._getAggregation(override) === 'quarter' ?
'3 months' : '1 ' + this._getAggregation(override);
var interval = this._getAggregation(override) === 'quarter'
? '3 months' : '1 ' + this._getAggregation(override);
const histogramSql = this._buildQueryTpl({
override: override,

View File

@@ -26,7 +26,7 @@ const irqQueryTpl = ctx => `
max(${ctx.column}) AS __cdb_max_val,
min(${ctx.column}) AS __cdb_min_val,
count(1) AS __cdb_total_rows,
${ctx.irq ? ctx.irq : `0`} AS __cdb_iqr
${ctx.irq ? ctx.irq : '0'} AS __cdb_iqr
FROM
(
SELECT *
@@ -72,7 +72,6 @@ module.exports = class NumericHistogram extends BaseHistogram {
return callback(null, histogramSql);
}
/**
* ctx: Object with the following values
* ctx.column -- Column for the histogram
@@ -85,10 +84,10 @@ module.exports = class NumericHistogram extends BaseHistogram {
* ctx.maxBins - If !full max bins to calculate [Optional]
*/
_buildQueryTpl (ctx) {
var extra_tables = ``;
var extra_queries = ``;
var extra_groupby = ``;
var extra_filter = ``;
var extra_tables = '';
var extra_queries = '';
var extra_groupby = '';
var extra_filter = '';
if (ctx.start < ctx.end) {
extra_filter = `
@@ -96,19 +95,19 @@ module.exports = class NumericHistogram extends BaseHistogram {
AND __ctx_query.${ctx.column} <= ${ctx.end}
`;
} else {
ctx.end = `__cdb_basics.__cdb_max_val`;
ctx.start = `__cdb_basics.__cdb_min_val`;
extra_groupby = `, __cdb_basics.__cdb_max_val, __cdb_basics.__cdb_min_val`;
extra_tables = `, __cdb_basics`;
ctx.end = '__cdb_basics.__cdb_max_val';
ctx.start = '__cdb_basics.__cdb_min_val';
extra_groupby = ', __cdb_basics.__cdb_max_val, __cdb_basics.__cdb_min_val';
extra_tables = ', __cdb_basics';
extra_queries = `WITH ${irqQueryTpl(ctx)}`;
}
if (ctx.bins <= 0) {
ctx.bins = `__cdb_basics.__cdb_bins_number`;
ctx.bins = '__cdb_basics.__cdb_bins_number';
ctx.irq = `percentile_disc(0.75) within group (order by ${ctx.column})
- percentile_disc(0.25) within group (order by ${ctx.column})`;
extra_groupby += `, __cdb_basics.__cdb_bins_number`;
extra_tables = `, __cdb_basics`;
extra_groupby += ', __cdb_basics.__cdb_bins_number';
extra_tables = ', __cdb_basics';
extra_queries = `WITH ${irqQueryTpl(ctx)}`;
}
@@ -188,5 +187,4 @@ ORDER BY 10;`;
return binStart;
}
};

View File

@@ -130,9 +130,9 @@ Aggregation.prototype.sql = function(psql, override, callback) {
}
var aggregationSql;
if (!!override.ownFilter) {
if (override.ownFilter) {
aggregationSql = [
"WITH",
'WITH',
[
filteredQueryTpl({
_isFloatColumn: this._isFloatColumn,
@@ -171,7 +171,7 @@ Aggregation.prototype.sql = function(psql, override, callback) {
].join('\n');
} else {
aggregationSql = [
"WITH",
'WITH',
[
filteredQueryTpl({
_isFloatColumn: this._isFloatColumn,

View File

@@ -29,7 +29,7 @@ var OverviewsDataviewMetaFactory = {
getFactory: function (queryRewriter, queryRewriteData, options) {
return new OverviewsDataviewFactory(queryRewriter, queryRewriteData, options);
},
}
};
module.exports = OverviewsDataviewMetaFactory;

View File

@@ -18,7 +18,7 @@ const VALID_OPERATIONS = {
function dataviewResult (ctx) {
switch (ctx.operation) {
case 'count':
return `sum(_feature_count)`;
return 'sum(_feature_count)';
case 'sum':
return `sum(${utils.handleFloatColumn(ctx)}*_feature_count)`;
case 'avg':
@@ -31,8 +31,8 @@ const formulaQueryTpl = ctx =>
`SELECT
${dataviewResult(ctx)} AS result,
${utils.countNULLs(ctx)} AS nulls_count
${ctx.isFloatColumn ? `,${utils.countInfinites(ctx)} AS infinities_count,` : ``}
${ctx.isFloatColumn ? `${utils.countNaNs(ctx)} AS nans_count` : ``}
${ctx.isFloatColumn ? `,${utils.countInfinites(ctx)} AS infinities_count,` : ''}
${ctx.isFloatColumn ? `${utils.countNaNs(ctx)} AS nans_count` : ''}
FROM (${ctx.query}) __cdb_formula`;
function Formula (query, options, queryRewriter, queryRewriteData, params, queries) {

View File

@@ -157,7 +157,6 @@ Histogram.prototype.sql = function(psql, override, callback) {
override = {};
}
if (this._columnType === null) {
this.getColumnType(psql, this.column, this.queries.no_filters, function (err, type) {
// assume numeric, will fail later
@@ -259,7 +258,7 @@ Histogram.prototype._buildQuery = function (override) {
}
var histogramSql = [
"WITH",
'WITH',
cteSql.join(',\n'),
histogramQueryTpl({
_isFloatColumn: this._columnType === 'float',

View File

@@ -106,7 +106,6 @@ module.exports.adjustLongitudeRange = adjustLongitudeRange;
module.exports.LATITUDE_MAX_VALUE = LATITUDE_MAX_VALUE;
module.exports.LONGITUDE_MAX_VALUE = LONGITUDE_UPPER_BOUND;
BBox.prototype.sql = function (rawSql) {
var bboxSql = filterQueryTpl({
_sql: rawSql,

View File

@@ -27,7 +27,6 @@ module.exports = class AggregationMapConfigAdapter {
return callback(err);
}
if (!this._shouldAdapt(mapConfig, params)) {
return callback(null, requestMapConfig);
}
@@ -101,8 +100,7 @@ module.exports = class AggregationMapConfigAdapter {
try {
aggregationSql = mapConfig.getAggregatedQuery(index);
}
catch (error) {
} catch (error) {
return reject(error);
}

View File

@@ -180,8 +180,8 @@ AnalysisMapConfigAdapter.prototype.getMapConfig = function(user, requestMapConfi
};
var SKIP_COLUMNS = {
'the_geom': true,
'the_geom_webmercator': true
the_geom: true,
the_geom_webmercator: true
};
function skipColumns (columnNames) {
@@ -279,7 +279,7 @@ function getLayerDataviews(layer, dataviews) {
function getDataviewsColumns (dataviews) {
return Object.keys(dataviews.reduce(function (columnsDict, dataview) {
getDataviewColumns(dataview).forEach(function (columnName) {
if (!!columnName) {
if (columnName) {
columnsDict[columnName] = true;
}
});

View File

@@ -5,7 +5,6 @@ function DataviewsWidgetsMapConfigAdapter() {
module.exports = DataviewsWidgetsMapConfigAdapter;
DataviewsWidgetsMapConfigAdapter.prototype.getMapConfig = function (user, requestMapConfig, params, context, callback) {
if (!shouldAdapt(requestMapConfig)) {
return callback(null, requestMapConfig);

View File

@@ -24,7 +24,6 @@ MapConfigNamedLayersAdapter.prototype.getMapConfig = function (user, requestMapC
function adaptLayer (layer, done) {
if (isNamedTypeLayer(layer)) {
if (!layer.options.name) {
return done(new Error('Missing Named Map `name` in layer options'));
}
@@ -63,7 +62,6 @@ MapConfigNamedLayersAdapter.prototype.getMapConfig = function (user, requestMapC
return done(unauthorizedError);
}
});
} else {
return done(null, {
datasource: false,
@@ -83,11 +81,10 @@ MapConfigNamedLayersAdapter.prototype.getMapConfig = function (user, requestMapC
return callback(new Error('Missing layers array from layergroup config'));
}
var layers = [],
currentLayerIndex = 0;
var layers = [];
var currentLayerIndex = 0;
layersResults.forEach(function (layersResult) {
layersResult.layers.forEach(function (layer) {
layers.push(layer);
if (layersResult.datasource) {
@@ -97,7 +94,6 @@ MapConfigNamedLayersAdapter.prototype.getMapConfig = function (user, requestMapC
}
currentLayerIndex++;
});
});
requestMapConfig.layers = layers;
@@ -106,7 +102,6 @@ MapConfigNamedLayersAdapter.prototype.getMapConfig = function (user, requestMapC
return callback(null, requestMapConfig);
}
var dbAuth = {};
if (_.some(layers, isNamedTypeLayer)) {
@@ -123,7 +118,6 @@ MapConfigNamedLayersAdapter.prototype.getMapConfig = function (user, requestMapC
context.datasource = datasourceBuilder.build();
return callback(null, requestMapConfig);
}
};
function isNamedTypeLayer (layer) {

View File

@@ -5,7 +5,6 @@ function SqlWrapMapConfigAdapter() {
module.exports = SqlWrapMapConfigAdapter;
SqlWrapMapConfigAdapter.prototype.getMapConfig = function (user, requestMapConfig, params, context, callback) {
if (requestMapConfig && Array.isArray(requestMapConfig.layers)) {
requestMapConfig.layers = requestMapConfig.layers.map(function (layer) {

View File

@@ -61,5 +61,4 @@ class VectorMapConfigAdapter {
}
}
module.exports = VectorMapConfigAdapter;

View File

@@ -68,9 +68,9 @@ module.exports = class NamedMapMapConfigProvider extends BaseMapConfigProvider {
if (this.config) {
try {
templateParams = Object.prototype.toString.call(this.config) === '[object String]' ?
JSON.parse(this.config) :
this.config;
templateParams = Object.prototype.toString.call(this.config) === '[object String]'
? JSON.parse(this.config)
: this.config;
} catch (e) {
const err = new Error('malformed config parameter, should be a valid JSON');
return callback(err);

View File

@@ -214,7 +214,7 @@ function getCdnUrls(serverMetadata, username, resource) {
}
return {
http: httpUrls,
https: httpsUrls,
https: httpsUrls
};
}
return null;
@@ -236,7 +236,7 @@ function getCdnDomain(serverMetadata, resource) {
}
return {
http: httpDomain,
https: httpsDomain,
https: httpsDomain
};
}
return null;

View File

@@ -8,7 +8,6 @@ function HealthCheck(disableFile) {
module.exports = HealthCheck;
HealthCheck.prototype.check = function (callback) {
fs.readFile(this.disableFile, function handleDisabledFile (err, data) {
var disabledError = null;

View File

@@ -2,9 +2,8 @@
var HealthCheck = require('./monitoring/health-check');
var WELCOME_MSG = "This is the CartoDB Maps API, " +
"see the documentation at http://docs.cartodb.com/cartodb-platform/maps-api.html";
var WELCOME_MSG = 'This is the CartoDB Maps API, ' +
'see the documentation at http://docs.cartodb.com/cartodb-platform/maps-api.html';
function ServerInfoController (versions) {
this.healthConfig = global.environment.health || {};
@@ -29,7 +28,7 @@ ServerInfoController.prototype.version = function(req, res) {
};
ServerInfoController.prototype.health = function (req, res) {
if (!!this.healthConfig.enabled) {
if (this.healthConfig.enabled) {
var startTime = Date.now();
this.healthCheck.check(function (err) {
var ok = !err;
@@ -42,7 +41,6 @@ ServerInfoController.prototype.health = function(req, res) {
response.err = err.message;
}
res.status(ok ? 200 : 503).send(response);
});
} else {
res.status(200).send({ enabled: false, ok: true });

View File

@@ -70,13 +70,13 @@ module.exports = {
api: [{
paths: [
'/api/v1',
'/user/:user/api/v1',
'/user/:user/api/v1'
],
// Base url for the Detached Maps API
// "/api/v1/map" is the new API,
map: [{
paths: [
'/map',
'/map'
]
}],
// Base url for the Templated Maps API

View File

@@ -18,9 +18,7 @@ module.exports = {
* @returns {StatsD|Object}
*/
getInstance: function (config) {
if (!this.instance) {
var instance;
if (config) {
@@ -31,7 +29,7 @@ module.exports = {
var last_msg = last_err.msg;
var this_msg = '' + err;
if (this_msg !== last_msg) {
debug("statsd client socket error: " + err);
debug('statsd client socket error: ' + err);
instance.last_error.count = 1;
instance.last_error.msg = this_msg;
} else {
@@ -40,7 +38,7 @@ module.exports = {
instance.last_error.interval = setInterval(function () {
var count = instance.last_error.count;
if (count > 1) {
debug("last statsd client socket error repeated " + count + " times");
debug('last statsd client socket error repeated ' + count + ' times');
instance.last_error.count = 1;
clearInterval(instance.last_error.interval);
instance.last_error.interval = null;

View File

@@ -9,7 +9,7 @@ function ProfilerProxy(opts) {
this.profile = !!opts.profile;
this.profiler = null;
if (!!opts.profile) {
if (opts.profile) {
this.profiler = new Profiler({ statsd_client: opts.statsd_client });
}
}
@@ -45,11 +45,11 @@ ProfilerProxy.prototype.sendStats = function() {
};
ProfilerProxy.prototype.toString = function () {
return this.profile ? this.profiler.toString() : "";
return this.profile ? this.profiler.toString() : '';
};
ProfilerProxy.prototype.toJSONString = function () {
return this.profile ? this.profiler.toJSONString() : "{}";
return this.profile ? this.profiler.toJSONString() : '{}';
};
module.exports = ProfilerProxy;

View File

@@ -188,5 +188,4 @@ module.exports = class LayergroupMetadata {
});
}
}
};

View File

@@ -24,7 +24,6 @@ function apply_filters_to_query(query, filters, bbox_filter) {
}
function OverviewsQueryRewriter (options) {
this.options = options;
}
@@ -59,31 +58,31 @@ function overviews_view_for_table(table, overviews_metadata, indent) {
overview_layers.push([overview_z_condition(z_lo, z_hi), ov_table]);
z_lo = z_hi;
}
overview_layers.push(["_vovw_z > " + z_lo, table]);
overview_layers.push(['_vovw_z > ' + z_lo, table]);
selects = overview_layers.map(function (condition_table) {
condition = condition_table[0];
ov_table = TableNameParser.parse(condition_table[1]);
ov_table.schema = ov_table.schema || parsed_table.schema;
var ov_identifier = TableNameParser.table_identifier(ov_table);
return indent + "SELECT * FROM " + ov_identifier + ", _vovw_scale WHERE " + condition;
return indent + 'SELECT * FROM ' + ov_identifier + ', _vovw_scale WHERE ' + condition;
});
return selects.join("\n"+indent+"UNION ALL\n");
return selects.join('\n' + indent + 'UNION ALL\n');
}
function overview_z_condition (z_lo, z_hi) {
if (z_lo !== null) {
if (z_lo === z_hi - 1) {
return "_vovw_z = " + z_hi;
return '_vovw_z = ' + z_hi;
} else {
return "_vovw_z > " + z_lo + " AND _vovw_z <= " + z_hi;
return '_vovw_z > ' + z_lo + ' AND _vovw_z <= ' + z_hi;
}
} else {
if (z_hi === 0) {
return "_vovw_z = " + z_hi;
return '_vovw_z = ' + z_hi;
} else {
return "_vovw_z <= " + z_hi;
return '_vovw_z <= ' + z_hi;
}
}
}
@@ -142,7 +141,6 @@ function replace_table_in_query(sql, old_table_name, replacement) {
return sql.replace(new RegExp(regexp, 'g'), replacement);
}
function replace_table_in_query_with_schema (query, table, schema, replacement) {
if (replacement) {
query = replace_table_in_query(query, table, replacement);
@@ -161,17 +159,17 @@ function replace_table_in_query_with_schema(query, table, schema, replacement) {
// be evaluated by the database server)
function overviews_query_with_zoom_expression (query, overviews, zoom_level_expression) {
var replaced_query = query;
var sql = "WITH\n _vovw_scale AS ( SELECT " + zoom_level_expression + " AS _vovw_z )";
var sql = 'WITH\n _vovw_scale AS ( SELECT ' + zoom_level_expression + ' AS _vovw_z )';
var replacement;
_.each(Object.keys(overviews), function (table) {
var table_overviews = overviews[table];
var table_view = overviews_view_name(table);
var schema = table_overviews.schema;
replacement = "(\n" + overviews_view_for_table(table, table_overviews) + "\n ) AS " + table_view;
replacement = '(\n' + overviews_view_for_table(table, table_overviews) + '\n ) AS ' + table_view;
replaced_query = replace_table_in_query_with_schema(replaced_query, table, schema, replacement);
});
if (replaced_query !== query) {
sql += "\n";
sql += '\n';
sql += replaced_query;
} else {
sql = query;
@@ -303,12 +301,12 @@ function should_use_overviews(query, data) {
function is_supported_query (sql) {
var basic_query =
/\s*SELECT\s+[\*a-z0-9_,\s]+?\s+FROM\s+((\"[^"]+\"|[a-z0-9_]+)\.)?(\"[^"]+\"|[a-z0-9_]+)\s*;?\s*/i;
var unwrapped_query = new RegExp("^"+basic_query.source+"$", 'i');
var unwrapped_query = new RegExp('^' + basic_query.source + '$', 'i');
// queries for named maps are wrapped like this:
var wrapped_query = new RegExp(
"^\\s*SELECT\\s+\\*\\s+FROM\\s+\\(" +
'^\\s*SELECT\\s+\\*\\s+FROM\\s+\\(' +
basic_query.source +
"\\)\\s+AS\\s+wrapped_query\\s+WHERE\\s+\\d+=1\\s*$",
'\\)\\s+AS\\s+wrapped_query\\s+WHERE\\s+\\d+=1\\s*$',
'i'
);
return !!(sql.match(unwrapped_query) || sql.match(wrapped_query));

View File

@@ -43,8 +43,8 @@ module.exports.columnCastTpl = function columnCastTpl(ctx) {
/** If the column type is float, ignore any non numeric result (infinity / NaN) */
module.exports.handleFloatColumn = function handleFloatColumn (ctx) {
return `${!ctx.isFloatColumn ? `${ctx.column}` :
`nullif(nullif(nullif(${ctx.column}, 'infinity'::float), '-infinity'::float), 'NaN'::float)`
return `${!ctx.isFloatColumn ? `${ctx.column}`
: `nullif(nullif(nullif(${ctx.column}, 'infinity'::float), '-infinity'::float), 'NaN'::float)`
}`;
};
@@ -55,15 +55,15 @@ module.exports.countNULLs = function countNULLs(ctx) {
/** Count only infinity (positive and negative) appearances */
module.exports.countInfinites = function countInfinites (ctx) {
return `${!ctx.isFloatColumn ? '0' :
`sum(CASE WHEN (${ctx.column} = 'infinity'::float OR ${ctx.column} = '-infinity'::float) THEN 1 ELSE 0 END)`
return `${!ctx.isFloatColumn ? '0'
: `sum(CASE WHEN (${ctx.column} = 'infinity'::float OR ${ctx.column} = '-infinity'::float) THEN 1 ELSE 0 END)`
}`;
};
/** Count only NaNs appearances */
module.exports.countNaNs = function countNaNs (ctx) {
return `${!ctx.isFloatColumn ? '0' :
`sum(CASE WHEN (${ctx.column} = 'NaN'::float) THEN 1 ELSE 0 END)`
return `${!ctx.isFloatColumn ? '0'
: `sum(CASE WHEN (${ctx.column} = 'NaN'::float) THEN 1 ELSE 0 END)`
}`;
};

View File

@@ -12,7 +12,6 @@ function quote_identifier_if_needed(txt) {
// Parse PostgreSQL table name (possibly quoted and with optional schema).+
// Returns { schema: 'schema_name', table: 'table_name' }
function parse_table_name (table) {
function split_as_quoted_parts (table_name) {
// parse table into 'parts' that may be quoted, each part
// in the parts array being an object { part: 'text', quoted: false/true }
@@ -24,8 +23,7 @@ function parse_table_name(table) {
i++;
parts[parts.length - 1].part += '"' + splitted[i];
}
}
else {
} else {
var is_quoted = (i > 0 && splitted[i - 1] === '') ||
(i < splitted.length - 1 && splitted[i + 1] === '');
parts.push({ part: splitted[i], quoted: is_quoted });

View File

@@ -51,7 +51,6 @@ function pointsWithTimeSQL(n, startTime, endTime, span = 0, x0 = 0.1, y0 = 0.1)
}
describe('aggregation', function () {
const POINTS_SQL_1 = `
select
x + 4 as cartodb_id,
@@ -513,7 +512,6 @@ describe('aggregation', function () {
return done(err);
}
assert.equal(typeof body.metadata, 'object');
assert.ok(Array.isArray(body.metadata.layers));
@@ -541,7 +539,7 @@ describe('aggregation', function () {
aggregation: {
placement: placement,
columns: {
'first_column': {
first_column: {
aggregate_function: 'sum',
aggregated_column: 'value'
}
@@ -563,7 +561,6 @@ describe('aggregation', function () {
return done(err);
}
assert.equal(typeof body.metadata, 'object');
assert.ok(Array.isArray(body.metadata.layers));
@@ -583,7 +580,7 @@ describe('aggregation', function () {
aggregation: {
placement: placement,
columns: {
'first_column': {
first_column: {
aggregate_function: 'sum',
aggregated_column: 'value'
}
@@ -952,7 +949,7 @@ describe('aggregation', function () {
aggregation: {
threshold: 1,
dimensions: {
value: "value"
value: 'value'
}
}
}
@@ -1024,7 +1021,7 @@ describe('aggregation', function () {
sql: pointsWithTimeSQL(nPoints, '2000-01-01T00:00:00+00', '2019-12-31T23:59:59+00', 0),
dates_as_numbers: true,
aggregation: {
threshold: 1,
threshold: 1
}
}
}
@@ -1065,7 +1062,7 @@ describe('aggregation', function () {
}
}
},
}
}
}
]);
@@ -1109,7 +1106,7 @@ describe('aggregation', function () {
}
}
},
}
}
}
]);
@@ -1280,14 +1277,18 @@ describe('aggregation', function () {
assert.ifError(err);
const expectedDimensions = {
dow:
{ params:
{ time: 'to_timestamp("date")',
{
params:
{
time: 'to_timestamp("date")',
timezone: 'utc',
units: 'dayOfWeek',
count: 1 },
count: 1
},
min: 4,
max: 7,
type: 'number' }
type: 'number'
}
};
assert.deepEqual(layergroup.metadata.layers[0].meta.stats.dimensions, expectedDimensions);
done();
@@ -1337,7 +1338,7 @@ describe('aggregation', function () {
month: {
column: 'date',
group: {
units: 'month',
units: 'month'
},
format: 'iso'
}
@@ -1382,7 +1383,7 @@ describe('aggregation', function () {
units: 'month',
timezone: '+7200'
},
format: 'iso',
format: 'iso'
}
}
@@ -1427,7 +1428,7 @@ describe('aggregation', function () {
units: 'hour',
timezone: '+7200'
},
format: 'iso',
format: 'iso'
}
}
@@ -1447,30 +1448,30 @@ describe('aggregation', function () {
const tileJSON = tile.toJSON();
const resultHours = tileJSON[0].features.map(f => f.properties.hour).sort();
assert.deepEqual(resultHours, [
"2018-01-01T00",
"2018-01-01T01",
"2018-01-01T02",
"2018-01-01T03",
"2018-01-01T04",
"2018-01-01T05",
"2018-01-01T06",
"2018-01-01T07",
"2018-01-01T08",
"2018-01-01T09",
"2018-01-01T10",
"2018-01-01T11",
"2018-01-01T12",
"2018-01-01T13",
"2018-01-01T14",
"2018-01-01T15",
"2018-01-01T16",
"2018-01-01T17",
"2018-01-01T18",
"2018-01-01T19",
"2018-01-01T20",
"2018-01-01T21",
"2018-01-01T22",
"2018-01-01T23"
'2018-01-01T00',
'2018-01-01T01',
'2018-01-01T02',
'2018-01-01T03',
'2018-01-01T04',
'2018-01-01T05',
'2018-01-01T06',
'2018-01-01T07',
'2018-01-01T08',
'2018-01-01T09',
'2018-01-01T10',
'2018-01-01T11',
'2018-01-01T12',
'2018-01-01T13',
'2018-01-01T14',
'2018-01-01T15',
'2018-01-01T16',
'2018-01-01T17',
'2018-01-01T18',
'2018-01-01T19',
'2018-01-01T20',
'2018-01-01T21',
'2018-01-01T22',
'2018-01-01T23'
]);
tileJSON[0].features.forEach(f => assert.equal(f.properties._cdb_feature_count, 4));
done();
@@ -1488,7 +1489,7 @@ describe('aggregation', function () {
placement: placement,
threshold: 1,
dimensions: {
value: "value"
value: 'value'
}
}
}
@@ -1526,7 +1527,7 @@ describe('aggregation', function () {
placement: placement,
threshold: 1,
dimensions: {
value2: "value"
value2: 'value'
}
}
}
@@ -1553,8 +1554,7 @@ describe('aggregation', function () {
});
});
it(`dimensions should trigger non-default aggregation`, function(done) {
it('dimensions should trigger non-default aggregation', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -1563,7 +1563,7 @@ describe('aggregation', function () {
aggregation: {
threshold: 1,
dimensions: {
value: "value"
value: 'value'
}
}
}
@@ -1592,7 +1592,7 @@ describe('aggregation', function () {
});
});
it(`aggregation columns should trigger non-default aggregation`, function(done) {
it('aggregation columns should trigger non-default aggregation', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -1879,7 +1879,7 @@ describe('aggregation', function () {
options: {
sql: POINTS_SQL_1,
aggregation: {
resolution: 'wadus',
resolution: 'wadus'
}
}
}
@@ -1904,9 +1904,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid resolution, should be a number greather than 0',
layer: {
"id": "wadus",
"index": 0,
"type": "mapnik"
id: 'wadus',
index: 0,
type: 'mapnik'
}
}]
});
@@ -1921,7 +1921,7 @@ describe('aggregation', function () {
options: {
sql: POINTS_SQL_1,
aggregation: {
placement: 'wadus',
placement: 'wadus'
}
}
}
@@ -1946,9 +1946,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid placement. Valid values: centroid, point-grid, point-sample',
layer: {
id: "layer0",
id: 'layer0',
index: 0,
type: "mapnik",
type: 'mapnik'
}
}]
});
@@ -1964,7 +1964,7 @@ describe('aggregation', function () {
options: {
sql: POINTS_SQL_1,
aggregation: {
threshold: 'wadus',
threshold: 'wadus'
}
}
}
@@ -1989,9 +1989,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid threshold, should be a number greather than 0',
layer: {
"id": "layer0",
"index": 0,
"type": "mapnik"
id: 'layer0',
index: 0,
type: 'mapnik'
}
}]
});
@@ -2010,9 +2010,9 @@ describe('aggregation', function () {
columns: {
'': {
aggregate_function: 'count',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
}
}
}
@@ -2037,9 +2037,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid column name, should be a non empty string',
layer: {
"id": "layer0",
"index": 0,
"type": "mapnik"
id: 'layer0',
index: 0,
type: 'mapnik'
}
}]
});
@@ -2056,11 +2056,11 @@ describe('aggregation', function () {
sql: POINTS_SQL_1,
aggregation: {
columns: {
'wadus_function': {
wadus_function: {
aggregate_function: 'wadus',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
}
}
}
@@ -2087,9 +2087,9 @@ describe('aggregation', function () {
message: 'Unsupported aggregation function wadus, ' +
'valid ones: count, avg, sum, min, max, mode',
layer: {
"id": "layer0",
"index": 0,
"type": "mapnik"
id: 'layer0',
index: 0,
type: 'mapnik'
}
}]
});
@@ -2106,11 +2106,11 @@ describe('aggregation', function () {
sql: POINTS_SQL_1,
aggregation: {
columns: {
'total_wadus': {
total_wadus: {
aggregate_function: 'sum',
aggregated_column: '',
aggregated_column: ''
}
}
},
}
}
}
@@ -2134,9 +2134,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid aggregated column, should be a non empty string',
layer: {
"id": "layer0",
"index": 0,
"type": "mapnik"
id: 'layer0',
index: 0,
type: 'mapnik'
}
}]
});
@@ -2145,7 +2145,6 @@ describe('aggregation', function () {
});
});
it('should skip aggregation w/o failing when is Vector Only MapConfig and layer has polygons',
function (done) {
this.mapConfig = createVectorMapConfig([
@@ -2341,7 +2340,6 @@ describe('aggregation', function () {
});
});
['centroid', 'point-sample', 'point-grid'].forEach(placement => {
it(`filters should work for ${placement} placement`, function (done) {
this.mapConfig = createVectorMapConfig([
@@ -2484,7 +2482,7 @@ describe('aggregation', function () {
});
});
it(`supports IN filters`, function(done) {
it('supports IN filters', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2525,7 +2523,7 @@ describe('aggregation', function () {
});
});
it(`supports NOT IN filters`, function(done) {
it('supports NOT IN filters', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2566,7 +2564,7 @@ describe('aggregation', function () {
});
});
it(`supports EQUAL filters`, function(done) {
it('supports EQUAL filters', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2607,7 +2605,7 @@ describe('aggregation', function () {
});
});
it(`supports NOT EQUAL filters`, function(done) {
it('supports NOT EQUAL filters', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2648,7 +2646,7 @@ describe('aggregation', function () {
});
});
it(`supports BETWEEN filters`, function(done) {
it('supports BETWEEN filters', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2692,7 +2690,7 @@ describe('aggregation', function () {
});
});
it(`supports RANGE filters`, function(done) {
it('supports RANGE filters', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2736,7 +2734,7 @@ describe('aggregation', function () {
});
});
it(`invalid filters cause errors`, function(done) {
it('invalid filters cause errors', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2779,9 +2777,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid filter parameter name: not_a_valid_parameter',
layer: {
id: "layer0",
id: 'layer0',
index: 0,
type: "mapnik",
type: 'mapnik'
}
}]
});
@@ -2790,7 +2788,7 @@ describe('aggregation', function () {
});
});
it(`filters on invalid columns cause errors`, function(done) {
it('filters on invalid columns cause errors', function (done) {
this.mapConfig = createVectorMapConfig([
{
type: 'cartodb',
@@ -2833,9 +2831,9 @@ describe('aggregation', function () {
type: 'layer',
message: 'Invalid filtered column: value',
layer: {
id: "layer0",
id: 'layer0',
index: 0,
type: "mapnik",
type: 'mapnik'
}
}]
});
@@ -2848,7 +2846,7 @@ describe('aggregation', function () {
it(`for ${placement} and no points between tiles has unique ids`, function (done) {
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -2895,13 +2893,12 @@ describe('aggregation', function () {
done();
});
});
});
it(`for ${placement} has unique ids save between tiles`, function (done) {
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -2966,7 +2963,6 @@ describe('aggregation', function () {
}
done();
});
});
});
@@ -2976,7 +2972,7 @@ describe('aggregation', function () {
const query = POINTS_SQL_GRID(z, resolution);
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3019,10 +3015,10 @@ describe('aggregation', function () {
const tile11 = JSON.parse(mvt.toGeoJSONSync(0));
// There needs to be 13 points
const count_features = ((tile) =>
const count_features = (tile) =>
tile.features.map(f => f.properties)
.map(f => f._cdb_feature_count)
.reduce((a,b) => a + b, 0));
.reduce((a, b) => a + b, 0);
const tile00Count = count_features(tile00);
const tile10Count = count_features(tile10);
@@ -3034,7 +3030,6 @@ describe('aggregation', function () {
});
});
});
});
});
@@ -3048,7 +3043,7 @@ describe('aggregation', function () {
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 1 },
buffersize: { mvt: 1 },
layers: [
{
type: 'cartodb',
@@ -3116,12 +3111,10 @@ describe('aggregation', function () {
});
});
});
});
});
it(`for ${placement} includes complete cells in buffer`, function (done) {
// use buffersize coincident with resolution, the buffer should include neighbour cells
const z = 2;
const resolution = 1;
@@ -3129,7 +3122,7 @@ describe('aggregation', function () {
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 1 },
buffersize: { mvt: 1 },
layers: [
{
type: 'cartodb',
@@ -3193,7 +3186,6 @@ describe('aggregation', function () {
});
});
});
});
});
@@ -3201,7 +3193,7 @@ describe('aggregation', function () {
// this test will fail due to !bbox! lack of accuracy if strict cell filtering is in place
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3239,7 +3231,7 @@ describe('aggregation', function () {
it(`for ${placement} points aggregated into correct cluster`, function (done) {
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3280,7 +3272,7 @@ describe('aggregation', function () {
global.environment.enabledFeatures.layerStats = true;
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3316,7 +3308,7 @@ describe('aggregation', function () {
global.environment.enabledFeatures.layerStats = true;
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3355,7 +3347,7 @@ describe('aggregation', function () {
global.environment.enabledFeatures.layerStats = true;
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3394,7 +3386,7 @@ describe('aggregation', function () {
global.environment.enabledFeatures.layerStats = true;
this.mapConfig = {
version: '1.6.0',
buffersize: { 'mvt': 0 },
buffersize: { mvt: 0 },
layers: [
{
type: 'cartodb',
@@ -3429,7 +3421,6 @@ describe('aggregation', function () {
});
});
});
});
});
});

View File

@@ -5,7 +5,6 @@ require('../../support/test-helper');
var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
describe('analyses controller', function () {
const mapConfig = {
version: '1.5.0',
@@ -110,7 +109,6 @@ describe('analyses controller', function () {
this.testClient.drain(done);
});
});
});
});

View File

@@ -6,7 +6,6 @@ const assert = require('../../support/assert');
const TestClient = require('../../support/test-client');
describe('analysis-filters-params', () => {
const CARTOCSS = `#layer {
marker-fill-opacity: 1;
marker-line-color: white;
@@ -23,13 +22,13 @@ describe('analysis-filters-params', () => {
version: '1.6.0',
layers: [
{
"type": "cartodb",
"options": {
"source": {
"id": "a1"
type: 'cartodb',
options: {
source: {
id: 'a1'
},
"cartocss": CARTOCSS,
"cartocss_version": "2.3.0"
cartocss: CARTOCSS,
cartocss_version: '2.3.0'
}
}
],
@@ -55,10 +54,10 @@ describe('analysis-filters-params', () => {
},
analyses: [
{
"id": "a1",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'a1',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]
@@ -77,7 +76,6 @@ describe('analysis-filters-params', () => {
}
};
it('should get a filtered histogram dataview with all filters', function (done) {
const testClient = new TestClient(mapConfig, 1234);
const testParams = Object.assign({}, params, {

View File

@@ -6,7 +6,6 @@ const assert = require('../../support/assert');
const TestClient = require('../../support/test-client');
describe('analysis-layers-dataviews', () => {
const CARTOCSS = `#layer {
marker-fill-opacity: 1;
marker-line-color: white;
@@ -23,13 +22,13 @@ describe('analysis-layers-dataviews', () => {
version: '1.6.0',
layers: [
{
"type": "cartodb",
"options": {
"source": {
"id": "a1"
type: 'cartodb',
options: {
source: {
id: 'a1'
},
"cartocss": CARTOCSS,
"cartocss_version": "2.3.0"
cartocss: CARTOCSS,
cartocss_version: '2.3.0'
}
}
],
@@ -46,10 +45,10 @@ describe('analysis-layers-dataviews', () => {
},
analyses: [
{
"id": "a1",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'a1',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]
@@ -61,7 +60,7 @@ describe('analysis-layers-dataviews', () => {
const params = {
filters: {
analyses: {
'a1': [
a1: [
{
type: 'range',
column: 'pop_max',

View File

@@ -7,34 +7,32 @@ var TestClient = require('../../support/test-client');
var dot = require('dot');
describe('analysis-layers-dataviews', function () {
var multitypeStyleTemplate = dot.template([
"#points['mapnik::geometry_type'=1] {",
" marker-fill-opacity: {{=it._opacity}};",
" marker-line-color: #FFF;",
" marker-line-width: 0.5;",
" marker-line-opacity: {{=it._opacity}};",
" marker-placement: point;",
" marker-type: ellipse;",
" marker-width: 8;",
" marker-fill: {{=it._color}};",
" marker-allow-overlap: true;",
"}",
' marker-fill-opacity: {{=it._opacity}};',
' marker-line-color: #FFF;',
' marker-line-width: 0.5;',
' marker-line-opacity: {{=it._opacity}};',
' marker-placement: point;',
' marker-type: ellipse;',
' marker-width: 8;',
' marker-fill: {{=it._color}};',
' marker-allow-overlap: true;',
'}',
"#lines['mapnik::geometry_type'=2] {",
" line-color: {{=it._color}};",
" line-width: 2;",
" line-opacity: {{=it._opacity}};",
"}",
' line-color: {{=it._color}};',
' line-width: 2;',
' line-opacity: {{=it._opacity}};',
'}',
"#polygons['mapnik::geometry_type'=3] {",
" polygon-fill: {{=it._color}};",
" polygon-opacity: {{=it._opacity}};",
" line-color: #FFF;",
" line-width: 0.5;",
" line-opacity: {{=it._opacity}};",
"}"
' polygon-fill: {{=it._color}};',
' polygon-opacity: {{=it._opacity}};',
' line-color: #FFF;',
' line-width: 0.5;',
' line-opacity: {{=it._opacity}};',
'}'
].join('\n'));
function cartocss (color, opacity) {
return multitypeStyleTemplate({
_color: color || '#F11810',
@@ -56,13 +54,13 @@ describe('analysis-layers-dataviews', function() {
var mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745"
type: 'cartodb',
options: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
}
],
@@ -79,10 +77,10 @@ describe('analysis-layers-dataviews', function() {
},
[
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]

View File

@@ -7,36 +7,34 @@ var TestClient = require('../../support/test-client');
var dot = require('dot');
describe('analysis-layers', function () {
var IMAGE_TOLERANCE_PER_MIL = 20;
var multitypeStyleTemplate = dot.template([
"#points['mapnik::geometry_type'=1] {",
" marker-fill-opacity: {{=it._opacity}};",
" marker-line-color: #FFF;",
" marker-line-width: 0.5;",
" marker-line-opacity: {{=it._opacity}};",
" marker-placement: point;",
" marker-type: ellipse;",
" marker-width: 8;",
" marker-fill: {{=it._color}};",
" marker-allow-overlap: true;",
"}",
' marker-fill-opacity: {{=it._opacity}};',
' marker-line-color: #FFF;',
' marker-line-width: 0.5;',
' marker-line-opacity: {{=it._opacity}};',
' marker-placement: point;',
' marker-type: ellipse;',
' marker-width: 8;',
' marker-fill: {{=it._color}};',
' marker-allow-overlap: true;',
'}',
"#lines['mapnik::geometry_type'=2] {",
" line-color: {{=it._color}};",
" line-width: 2;",
" line-opacity: {{=it._opacity}};",
"}",
' line-color: {{=it._color}};',
' line-width: 2;',
' line-opacity: {{=it._opacity}};',
'}',
"#polygons['mapnik::geometry_type'=3] {",
" polygon-fill: {{=it._color}};",
" polygon-opacity: {{=it._opacity}};",
" line-color: #FFF;",
" line-width: 0.5;",
" line-opacity: {{=it._opacity}};",
"}"
' polygon-fill: {{=it._color}};',
' polygon-opacity: {{=it._opacity}};',
' line-color: #FFF;',
' line-width: 0.5;',
' line-opacity: {{=it._opacity}};',
'}'
].join('\n'));
function cartocss (color, opacity) {
return multitypeStyleTemplate({
_color: color || '#F11810',
@@ -64,23 +62,23 @@ describe('analysis-layers', function() {
mapConfig: mapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745"
type: 'cartodb',
options: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
}
],
{},
[
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]
@@ -94,30 +92,30 @@ describe('analysis-layers', function() {
mapConfig: mapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
}
],
{},
[
{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"radius": 50000
radius: 50000
}
}
]
@@ -127,7 +125,6 @@ describe('analysis-layers', function() {
useCases.forEach(function (useCase) {
it('should implement use case: "' + useCase.desc + '"', function (done) {
var testClient = new TestClient(useCase.mapConfig, 1234);
var tile = useCase.tile || TILE_ANALYSIS_TABLES;
@@ -176,13 +173,11 @@ describe('analysis-layers', function() {
}
};
testClient.getLayergroup({ response: PERMISSION_DENIED_RESPONSE }, function (err, layergroupResult) {
assert.ok(!err, err);
assert.deepEqual(
layergroupResult.errors,
["Analysis requires authentication with API key: permission denied."]
['Analysis requires authentication with API key: permission denied.']
);
testClient.drain(done);
@@ -225,29 +220,29 @@ describe('analysis-layers', function() {
mapConfig: mapConfig(
[
{
"type": "cartodb",
"options": {
"sql": "select * from populated_places_simple_reduced",
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
type: 'cartodb',
options: {
sql: 'select * from populated_places_simple_reduced',
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
},
{
"type": "cartodb",
"options": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745"
type: 'cartodb',
options: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
},
{
"type": "cartodb",
"options": {
"sql": "select * from populated_places_simple_reduced",
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
type: 'cartodb',
options: {
sql: 'select * from populated_places_simple_reduced',
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
}
],
@@ -273,10 +268,10 @@ describe('analysis-layers', function() {
},
[
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]
@@ -336,24 +331,24 @@ describe('analysis-layers', function() {
var testClient = new TestClient(mapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745"
type: 'cartodb',
options: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
"sql_wrap": "SELECT * FROM (<%= sql %>) __wrapped WHERE adm0cap = 1",
"cartocss": DEFAULT_MULTITYPE_STYLE,
"cartocss_version": "2.3.0"
sql_wrap: 'SELECT * FROM (<%= sql %>) __wrapped WHERE adm0cap = 1',
cartocss: DEFAULT_MULTITYPE_STYLE,
cartocss_version: '2.3.0'
}
}
],
{},
[
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]

View File

@@ -8,8 +8,6 @@ var dot = require('dot');
var debug = require('debug')('windshaft:cartodb:test');
describe('analysis-layers use cases', function () {
var multitypeStyleTemplate = dot.template(
`#points['mapnik::geometry_type'=1] {
marker-fill-opacity: {{=it._opacity}};
@@ -36,7 +34,6 @@ describe('analysis-layers use cases', function () {
}`
);
function cartocss (color, opacity) {
return multitypeStyleTemplate({
_color: color || '#F11810',
@@ -267,11 +264,10 @@ describe('analysis-layers use cases', function () {
];
useCases.forEach(function (useCase) {
if (!!useCase.skip) {
if (useCase.skip) {
return debug(JSON.stringify(useCase.mapConfig, null, 4));
}
it(`should implement use case: '${useCase.desc}'`, function (done) {
var testClient = new TestClient(useCase.mapConfig, 1234);
var tile = useCase.tile || TILE_ANALYSIS_TABLES;

View File

@@ -33,30 +33,30 @@ describe('analysis-layers error cases', function() {
var mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "INVALID-SOURCE-ID"
type: 'cartodb',
options: {
source: {
id: 'INVALID-SOURCE-ID'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
{},
[
{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"radius": 50000
radius: 50000
}
}
]
@@ -78,20 +78,20 @@ describe('analysis-layers error cases', function() {
var mapConfig = createMapConfig(
[
{
"type": "http",
"options": {
"urlTemplate": "http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png",
"subdomains": "abcd"
type: 'http',
options: {
urlTemplate: 'http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png',
subdomains: 'abcd'
}
},
{
"type": "cartodb",
"options": {
"source": {
"id": "ID-FOR-NONEXISTENT-ANALYSIS"
type: 'cartodb',
options: {
source: {
id: 'ID-FOR-NONEXISTENT-ANALYSIS'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}
]
@@ -116,18 +116,18 @@ describe('analysis-layers error cases', function() {
var mapConfig = createMapConfig(
[
{
"type": "http",
"options": {
"urlTemplate": "http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png",
"subdomains": "abcd"
type: 'http',
options: {
urlTemplate: 'http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png',
subdomains: 'abcd'
}
},
{
"type": "cartodb",
"options": {
"sql": "select * from populated_places_simple_reduced",
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
type: 'cartodb',
options: {
sql: 'select * from populated_places_simple_reduced',
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
@@ -161,30 +161,30 @@ describe('analysis-layers error cases', function() {
var mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
{},
[
{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "HEAD",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: 'HEAD',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"radius": 50000
radius: 50000
}
}
]
@@ -213,32 +213,31 @@ describe('analysis-layers error cases', function() {
});
});
it('camshaft: should return error: Missing required param "radius"; with context', function (done) {
var mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
{},
[
{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "HEAD2",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: 'HEAD2',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
}
@@ -268,30 +267,30 @@ describe('analysis-layers error cases', function() {
it('should return missing param error of outer node indicating the node_id and context', function (done) {
var mapConfig = createMapConfig([{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}], {}, [{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "HEAD2",
"type": "buffer",
"params": {
"source": {
"id": "HEAD3",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: 'HEAD2',
type: 'buffer',
params: {
source: {
id: 'HEAD3',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"radius": 10
radius: 10
}
}
}
@@ -321,33 +320,33 @@ describe('analysis-layers error cases', function() {
it('should return invalid param type error of inner node indicating the node_id and context', function (done) {
var mapConfig = createMapConfig([{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}], {}, [{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "HEAD2",
"type": "buffer",
"params": {
"source": {
"id": "HEAD3",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: 'HEAD2',
type: 'buffer',
params: {
source: {
id: 'HEAD3',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"radius": 'invalid_radius'
radius: 'invalid_radius'
}
},
"radius": 10
radius: 10
}
}]);
@@ -377,41 +376,41 @@ describe('analysis-layers error cases', function() {
it('should return "function does not exist" indicating the node_id and context', function (done) {
var mapConfig = createMapConfig([{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": '#polygons { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#polygons { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}], {}, [{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "HEAD2",
"type": "buffer",
"params": {
"source": {
"id": "HEAD3",
"type": 'deprecated-sql-function',
"params": {
"id": "HEAD4",
"function_name": 'DEP_EXT_does_not_exist_fn',
"primary_source": {
"type": 'source',
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: 'HEAD2',
type: 'buffer',
params: {
source: {
id: 'HEAD3',
type: 'deprecated-sql-function',
params: {
id: 'HEAD4',
function_name: 'DEP_EXT_does_not_exist_fn',
primary_source: {
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"function_args": ['wadus']
function_args: ['wadus']
}
},
"radius": 10
radius: 10
}
},
"radius": 10
radius: 10
}
}]);
@@ -438,7 +437,4 @@ describe('analysis-layers error cases', function() {
testClient.drain(done);
});
});
});

View File

@@ -17,7 +17,6 @@ describe('named-maps analysis', function() {
server = new CartodbWindshaft(serverOptions);
});
var IMAGE_TOLERANCE_PER_MIL = 20;
var username = 'localhost';
@@ -30,13 +29,13 @@ describe('named-maps analysis', function() {
version: '1.5.0',
layers: [
{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": '#buffer { polygon-fill: red; }',
"cartocss_version": "2.3.0"
cartocss: '#buffer { polygon-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
@@ -53,17 +52,17 @@ describe('named-maps analysis', function() {
},
analyses: [
{
"id": "HEAD",
"type": "buffer",
"params": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: 'HEAD',
type: 'buffer',
params: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
},
"radius": 50000
radius: 50000
}
}
]
@@ -162,7 +161,6 @@ describe('named-maps analysis', function() {
return done();
}
);
});
afterEach(function (done) {
@@ -196,7 +194,6 @@ describe('named-maps analysis', function() {
assert.ok(!err, err);
done();
});
}
);
});
@@ -258,7 +255,6 @@ describe('named-maps analysis', function() {
assert.ok(!err, err);
done();
});
}
);
});
@@ -314,11 +310,9 @@ describe('named-maps analysis', function() {
}
);
done();
}
);
});
});
describe('auto-instantiation', function () {
@@ -333,5 +327,4 @@ describe('named-maps analysis', function() {
});
});
});
});

View File

@@ -8,81 +8,81 @@ var TestClient = require('../../support/test-client');
describe('analysis-layers regressions', function () {
it('should return a complete list of nodes from analysis', function (done) {
var mapConfig = {
"version": "1.5.0",
"layers": [
version: '1.5.0',
layers: [
{
"type": "cartodb",
"options": {
"cartocss": TestClient.CARTOCSS.POINTS,
"cartocss_version": "2.1.1",
"interactivity": [],
"source": {
"id": "a4"
type: 'cartodb',
options: {
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.1.1',
interactivity: [],
source: {
id: 'a4'
}
}
},
{
"type": "cartodb",
"options": {
"cartocss": TestClient.CARTOCSS.POINTS,
"cartocss_version": "2.1.0",
"interactivity": [],
"source": {
"id": "b1"
type: 'cartodb',
options: {
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.1.0',
interactivity: [],
source: {
id: 'b1'
}
}
}
],
"dataviews": {
"74493a30-4679-4b72-a60c-b6f808b57c98": {
"type": "histogram",
"source": {
"id": "b0"
dataviews: {
'74493a30-4679-4b72-a60c-b6f808b57c98': {
type: 'histogram',
source: {
id: 'b0'
},
"options": {
"column": "customer_value",
"bins": 10
options: {
column: 'customer_value',
bins: 10
}
}
},
"analyses": [
analyses: [
{
"id": "a4",
"type": "point-in-polygon",
"params": {
"polygons_source": {
"id": "a3",
"type": "buffer",
"params": {
"source": {
"id": "a2",
"type": "centroid",
"params": {
"source": {
"id": "b1",
"type": "kmeans",
"params": {
"source": {
"id": "b0",
"type": "source",
"params": {
"query": "SELECT * FROM populated_places_simple_reduced"
id: 'a4',
type: 'point-in-polygon',
params: {
polygons_source: {
id: 'a3',
type: 'buffer',
params: {
source: {
id: 'a2',
type: 'centroid',
params: {
source: {
id: 'b1',
type: 'kmeans',
params: {
source: {
id: 'b0',
type: 'source',
params: {
query: 'SELECT * FROM populated_places_simple_reduced'
}
},
"clusters": 5
clusters: 5
}
},
"category_column": "cluster_no"
category_column: 'cluster_no'
}
},
"radius": 200000
radius: 200000
}
},
"points_source": {
"id": "customer_home_locations",
"type": "source",
"params": {
"query": "SELECT * FROM populated_places_simple_reduced"
points_source: {
id: 'customer_home_locations',
type: 'source',
params: {
query: 'SELECT * FROM populated_places_simple_reduced'
}
}
}
@@ -113,5 +113,4 @@ describe('analysis-layers regressions', function() {
testClient.drain(done);
});
});
});

View File

@@ -39,8 +39,8 @@ function createRequest(layergroup, userHost, apiKey) {
}
var layergroupUrl = '/api/v1/map';
var pointSqlMaster = "select * from test_table_private_1";
var pointSqlPublic = "select * from test_table";
var pointSqlMaster = 'select * from test_table_private_1';
var pointSqlPublic = 'select * from test_table';
var keysToDelete;
describe('Basic authorization use cases', function () {
@@ -58,7 +58,7 @@ describe('Basic authorization use cases', function () {
testHelper.deleteRedisKeys(keysToDelete, done);
});
it("succeed with master", function (done) {
it('succeed with master', function (done) {
var layergroup = singleLayergroupConfig(pointSqlMaster, '#layer { marker-fill:red; }');
assert.response(server,
@@ -81,8 +81,7 @@ describe('Basic authorization use cases', function () {
);
});
it("succeed with default - sending default_public", function (done) {
it('succeed with default - sending default_public', function (done) {
var layergroup = singleLayergroupConfig(pointSqlPublic, '#layer { marker-fill:red; }');
assert.response(server,
@@ -105,7 +104,7 @@ describe('Basic authorization use cases', function () {
);
});
it("fail with non-existent api key", function (done) {
it('fail with non-existent api key', function (done) {
var layergroup = singleLayergroupConfig(pointSqlPublic, '#layer { marker-fill:red; }');
assert.response(server,
@@ -124,7 +123,7 @@ describe('Basic authorization use cases', function () {
);
});
it("fail with default", function (done) {
it('fail with default', function (done) {
var layergroup = singleLayergroupConfig(pointSqlMaster, '#layer { marker-fill:red; }');
assert.response(server,
@@ -141,7 +140,7 @@ describe('Basic authorization use cases', function () {
});
describe('No api key provided - fallback to default_public', function () {
it("succeed with default - public dataset", function (done) {
it('succeed with default - public dataset', function (done) {
var layergroup = singleLayergroupConfig(pointSqlPublic, '#layer { marker-fill:red; }');
assert.response(server,
@@ -164,7 +163,7 @@ describe('Basic authorization use cases', function () {
);
});
it("fail with default - private dataset", function (done) {
it('fail with default - private dataset', function (done) {
var layergroup = singleLayergroupConfig(pointSqlMaster, '#layer { marker-fill:red; }');
assert.response(server,

View File

@@ -39,7 +39,6 @@ describe('authorization', function() {
});
});
it('should fail getting a named map tile with default apikey token', function (done) {
const apikeyTokenCreate = 'regular1';
const apikeyTokenGet = 'default_public';
@@ -69,7 +68,6 @@ describe('authorization', function() {
};
testClientGet.getTile(0, 0, 0, params, function (err, res, body) {
assert.ifError(err);
assert.ok(body.hasOwnProperty('errors'));
@@ -305,8 +303,8 @@ describe('authorization', function() {
],
analyses: [
{
id: "HEAD1",
type: "buffer",
id: 'HEAD1',
type: 'buffer',
params: {
source: {
id: 'HEAD2',
@@ -333,7 +331,6 @@ describe('authorization', function() {
describe('Named maps', function () {
describe('LIST Named maps', function () {
it('should fail while listing named maps with a regular apikey token', function (done) {
const apikeyToken = 'regular1';
@@ -418,7 +415,7 @@ describe('authorization', function() {
options: {
sql: 'select * from test_table_localhost_regular1',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0',
cartocss_version: '2.3.0'
}
}]
}
@@ -508,7 +505,7 @@ describe('authorization', function() {
options: {
sql: 'select * from test_table_localhost_regular1',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0',
cartocss_version: '2.3.0'
}
}]
}
@@ -653,7 +650,7 @@ describe('authorization', function() {
options: {
sql: 'select * from test_table_localhost_regular1',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0',
cartocss_version: '2.3.0'
}
}]
}
@@ -798,7 +795,7 @@ describe('authorization', function() {
options: {
sql: 'select * from test_table_localhost_regular1',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0',
cartocss_version: '2.3.0'
}
}]
}
@@ -928,7 +925,6 @@ describe('authorization', function() {
);
});
});
});
});
});

View File

@@ -39,13 +39,13 @@ function createMapConfig (bufferSize, cartocss) {
version: '1.6.0',
buffersize: bufferSize,
layers: [{
type: "cartodb",
type: 'cartodb',
options: {
sql: [
'select',
' *',
'from',
' populated_places_simple_reduced',
' populated_places_simple_reduced'
].join('\n'),
cartocss: cartocss,
cartocss_version: '2.3.0',
@@ -185,15 +185,15 @@ function createBufferSizeTemplate (name, buffersize, placeholders, cartocss) {
cartocss = cartocss || CARTOCSS_LABELS;
return {
"version": "0.0.1",
"name": name,
"placeholders": placeholders || {
"buffersize": {
"type": "number",
"default": 0
version: '0.0.1',
name: name,
placeholders: placeholders || {
buffersize: {
type: 'number',
default: 0
}
},
"layergroup": createMapConfig(buffersize)
layergroup: createMapConfig(buffersize)
};
}
@@ -229,9 +229,9 @@ describe('buffer size per format for named maps', function () {
template: createBufferSizeTemplate('named-default-buffer-size-by-format', {
png: '<%= buffersize_png %>'
}, {
"buffersize_png": {
"type": "number",
"default": "0"
buffersize_png: {
type: 'number',
default: '0'
}
}),
assert: function (tile, callback) {
@@ -247,9 +247,9 @@ describe('buffer size per format for named maps', function () {
template: createBufferSizeTemplate('named-custom-buffer-size-by-format', {
png: '<%= buffersize_png %>'
}, {
"buffersize_png": {
"type": "number",
"default": "0"
buffersize_png: {
type: 'number',
default: '0'
}
}),
assert: function (tile, callback) {
@@ -266,9 +266,9 @@ describe('buffer size per format for named maps', function () {
template: createBufferSizeTemplate('named-default-buffer-size-by-format-gridjson', {
'grid.json': '<%= buffersize_gridjson %>'
}, {
"buffersize_gridjson": {
"type": "number",
"default": "0"
buffersize_gridjson: {
type: 'number',
default: '0'
}
}),
assert: function (tile, callback) {
@@ -285,9 +285,9 @@ describe('buffer size per format for named maps', function () {
template: createBufferSizeTemplate('named-custom-buffer-size-by-format-gridjson', {
'grid.json': '<%= buffersize_gridjson %>'
}, {
"buffersize_gridjson": {
"type": "number",
"default": "0"
buffersize_gridjson: {
type: 'number',
default: '0'
}
}),
assert: function (tile, callback) {
@@ -322,7 +322,6 @@ describe('buffer size per format for named maps', function () {
});
});
describe('buffer size per format for named maps w/o placeholders', function () {
let testClient;
@@ -454,7 +453,7 @@ describe('buffer size per format for named maps w/o placeholders', function () {
assert: function (tile, callback) {
assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
}
},
}
];

View File

@@ -18,7 +18,6 @@ describe('get requests with cache headers', function() {
server.setMaxListeners(0);
});
var keysToDelete;
beforeEach(function () {
keysToDelete = {};
@@ -34,22 +33,22 @@ describe('get requests with cache headers', function() {
var mapConfigs = [
{
"description": "cache headers should be present",
"cache_headers": {
"x_cache_channel": {
"db_name": "test_windshaft_cartodb_user_1_db",
"tables": ["public.test_table"]
description: 'cache headers should be present',
cache_headers: {
x_cache_channel: {
db_name: 'test_windshaft_cartodb_user_1_db',
tables: ['public.test_table']
},
"surrogate_keys": "t:77pJnX"
surrogate_keys: 't:77pJnX'
},
"data":
data:
{
version: '1.5.0',
layers: [
{
options: {
source: {
id: "2570e105-7b37-40d2-bdf4-1af889598745"
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
sql: 'select * from test_table limit 2',
cartocss: '#layer { marker-fill:red; }',
@@ -66,33 +65,33 @@ describe('get requests with cache headers', function() {
],
analyses: [
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from test_table limit 2"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from test_table limit 2'
}
}
]
},
}
},
{
"description": "cache headers should be present and be composed with source table name",
"cache_headers": {
"x_cache_channel": {
"db_name": "test_windshaft_cartodb_user_1_db",
"tables": ["public.analysis_2f13a3dbd7_9eb239903a1afd8a69130d1ece0fc8b38de8592d",
"public.test_table"]
description: 'cache headers should be present and be composed with source table name',
cache_headers: {
x_cache_channel: {
db_name: 'test_windshaft_cartodb_user_1_db',
tables: ['public.analysis_2f13a3dbd7_9eb239903a1afd8a69130d1ece0fc8b38de8592d',
'public.test_table']
},
"surrogate_keys": "t:77pJnX t:iL4eth"
surrogate_keys: 't:77pJnX t:iL4eth'
},
"data":
data:
{
version: '1.5.0',
layers: [
{
options: {
source: {
id: "2570e105-7b37-40d2-bdf4-1af889598745"
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
sql: 'select * from test_table limit 2',
cartocss: '#layer { marker-fill:red; }',
@@ -109,16 +108,16 @@ describe('get requests with cache headers', function() {
],
analyses: [
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "buffer",
"params": {
"source": {
"type": "source",
"params": {
"query": "select * from test_table limit 2"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'buffer',
params: {
source: {
type: 'source',
params: {
query: 'select * from test_table limit 2'
}
},
"radius": 50000
radius: 50000
}
}
]
@@ -137,10 +136,10 @@ describe('get requests with cache headers', function() {
function getRequest (url, addApiKey, callbackName) {
var params = {};
if (!!addApiKey) {
if (addApiKey) {
params.api_key = '1234';
}
if (!!callbackName) {
if (callbackName) {
params.callback = callbackName;
}
@@ -288,7 +287,6 @@ describe('get requests with cache headers', function() {
});
describe('cache headers should NOT be present', function () {
it('/', function (done) {
assert.response(
server,
@@ -326,7 +324,6 @@ describe('get requests with cache headers', function() {
});
describe('with named maps', function () {
var templateName = 'x_cache';
beforeEach(function (done) {
@@ -378,7 +375,6 @@ describe('get requests with cache headers', function() {
);
});
it('/api/v1/map/named/:template_id Named map retrieval', function (done) {
assert.response(
server,

View File

@@ -11,7 +11,6 @@ var CartodbWindshaft = require('../../../lib/server');
var nock = require('nock');
describe('templates surrogate keys', function () {
var serverOptions = require('../../../lib/server-options');
// Enable Varnish purge for tests
@@ -61,12 +60,16 @@ describe('templates surrogate keys', function() {
]
}
};
var templateUpdated = _.extend({}, template, {layergroup: {layers: [{
var templateUpdated = _.extend({}, template, {
layergroup: {
layers: [{
type: 'plain',
options: {
color: 'red'
}
}]} });
}]
}
});
var expectedBody = { template_id: expectedTemplateId };
var varnishHttpUrl = [
@@ -128,8 +131,7 @@ describe('templates surrogate keys', function() {
);
}
it("invalidates surrogate keys on template update", function(done) {
it('invalidates surrogate keys on template update', function (done) {
var scope = nock(varnishHttpUrl)
.intercept('/key', 'PURGE')
.matchHeader('Invalidation-Match', invalidationMatchHeader)
@@ -194,8 +196,7 @@ describe('templates surrogate keys', function() {
);
});
it("invalidates surrogate on template deletion", function(done) {
it('invalidates surrogate on template deletion', function (done) {
var scope = nock(varnishHttpUrl)
.intercept('/key', 'PURGE')
.matchHeader('Invalidation-Match', invalidationMatchHeader)
@@ -254,8 +255,7 @@ describe('templates surrogate keys', function() {
);
});
it("should update template even if surrogate key invalidation fails", function(done) {
it('should update template even if surrogate key invalidation fails', function (done) {
var scope = nock(varnishHttpUrl)
.intercept('/key', 'PURGE')
.matchHeader('Invalidation-Match', invalidationMatchHeader)
@@ -319,5 +319,4 @@ describe('templates surrogate keys', function() {
}
);
});
});

View File

@@ -400,7 +400,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -415,7 +415,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -430,7 +430,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -445,7 +445,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -460,7 +460,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -475,7 +475,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -490,7 +490,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -505,7 +505,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -523,7 +523,7 @@ describe('cluster', function () {
expressions: {
max_value: {
aggregate_function: 'max',
aggregated_column: 'value',
aggregated_column: 'value'
}
}
},
@@ -555,12 +555,12 @@ describe('cluster', function () {
return done(err);
}
const sort_f = ((a, b) => {
const sort_f = (a, b) => {
return (a._cdb_feature_count < b._cdb_feature_count) ||
(a._cdb_feature_count === b._cdb_feature_count &&
(a.type < b.type ||
a.type === b.type && a.max_value < b.max_value));
});
};
assert.deepStrictEqual(body.rows.sort(sort_f), expected.sort(sort_f));
@@ -621,7 +621,6 @@ describe('cluster', function () {
]
};
const expectedAggregatedColumnError = {
errors: ['Invalid aggregation input, aggregated column should be an string'],
errors_with_context: [

View File

@@ -20,7 +20,7 @@ describe('custom middlewares', function () {
api: [{
paths: [
'/api/v1',
'/user/:user/api/v1',
'/user/:user/api/v1'
],
middlewares: [
function teapot () {
@@ -33,7 +33,7 @@ describe('custom middlewares', function () {
// "/api/v1/map" is the new API,
map: [{
paths: [
'/map',
'/map'
]
}],
// Base url for the Templated Maps API
@@ -123,13 +123,13 @@ describe('custom middlewares', function () {
api: [{
paths: [
'/api/v1',
'/user/:user/api/v1',
'/user/:user/api/v1'
],
// Base url for the Detached Maps API
// "/api/v1/map" is the new API,
map: [{
paths: [
'/map',
'/map'
],
middlewares: [
function teapot () {
@@ -189,7 +189,7 @@ describe('custom middlewares', function () {
assert.deepEqual(body, { template_id: templateid });
helper.deleteRedisKeys({ ['map_tpl|localhost']: 0 }, done);
helper.deleteRedisKeys({ 'map_tpl|localhost': 0 }, done);
});
});
@@ -231,13 +231,13 @@ describe('custom middlewares', function () {
api: [{
paths: [
'/api/v1',
'/user/:user/api/v1',
'/user/:user/api/v1'
],
// Base url for the Detached Maps API
// "/api/v1/map" is the new API,
map: [{
paths: [
'/map',
'/map'
]
}],
// Base url for the Templated Maps API
@@ -324,7 +324,7 @@ describe('custom middlewares', function () {
assert.ok(body.layergroupid);
helper.deleteRedisKeys({ ['user:localhost:mapviews:global']: 5 }, done);
helper.deleteRedisKeys({ 'user:localhost:mapviews:global': 5 }, done);
});
});
});

View File

@@ -5,7 +5,6 @@ var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
describe('aggregations happy cases', function () {
afterEach(function (done) {
if (this.testClient) {
this.testClient.drain(done);
@@ -50,7 +49,6 @@ describe('aggregations happy cases', function() {
operations.forEach(function (operation) {
it('should be able to use "' + operation + '" as aggregation operation', function (done) {
this.testClient = new TestClient(aggregationOperationMapConfig(operation));
this.testClient.getDataview('adm0name', { own_filter: 0 }, function (err, aggregation) {
assert.ok(!err, err);
@@ -100,7 +98,7 @@ describe('aggregations happy cases', function() {
});
});
var operations_and_values = {'count': 9, 'sum': 45, 'avg': 5, 'max': 9, 'min': 1};
var operations_and_values = { count: 9, sum: 45, avg: 5, max: 9, min: 1 };
var query_other = [
'select generate_series(1,3) as val, \'other_a\' as cat, NULL as the_geom_webmercator',
@@ -140,11 +138,11 @@ describe('aggregations happy cases', function() {
});
var widgetSearchExpects = {
'count': [ { category: 'other_a', value: 3 } ],
'sum': [ { category: 'other_a', value: 6 } ],
'avg': [ { category: 'other_a', value: 2 } ],
'max': [ { category: 'other_a', value: 3 } ],
'min': [ { category: 'other_a', value: 1 } ]
count: [{ category: 'other_a', value: 3 }],
sum: [{ category: 'other_a', value: 6 }],
avg: [{ category: 'other_a', value: 2 }],
max: [{ category: 'other_a', value: 3 }],
min: [{ category: 'other_a', value: 1 }]
};
Object.keys(operations_and_values).forEach(function (operation) {
@@ -170,7 +168,6 @@ describe('aggregations happy cases', function() {
});
describe('aggregation-dataview: special float values', function () {
afterEach(function (done) {
if (this.testClient) {
this.testClient.drain(done);
@@ -191,13 +188,13 @@ describe('aggregation-dataview: special float values', function() {
var mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "a0"
type: 'cartodb',
options: {
source: {
id: 'a0'
},
"cartocss": "#points { marker-width: 10; marker-fill: red; }",
"cartocss_version": "2.3.0"
cartocss: '#points { marker-width: 10; marker-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
@@ -227,10 +224,10 @@ describe('aggregation-dataview: special float values', function() {
},
[
{
"id": "a0",
"type": "source",
"params": {
"query": [
id: 'a0',
type: 'source',
params: {
query: [
'SELECT',
' null::geometry the_geom_webmercator,',
' CASE',
@@ -247,10 +244,10 @@ describe('aggregation-dataview: special float values', function() {
].join('\n')
}
}, {
"id": "a1",
"type": "source",
"params": {
"query": [
id: 'a1',
type: 'source',
params: {
query: [
'SELECT',
' null::geometry the_geom_webmercator,',
' CASE',
@@ -323,13 +320,13 @@ describe('aggregation dataview tuned by categories query param', function () {
version: '1.5.0',
layers: [
{
type: "cartodb",
type: 'cartodb',
options: {
source: {
"id": "a0"
id: 'a0'
},
cartocss: "#points { marker-width: 10; marker-fill: red; }",
cartocss_version: "2.3.0"
cartocss: '#points { marker-width: 10; marker-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
@@ -348,8 +345,8 @@ describe('aggregation dataview tuned by categories query param', function () {
},
analyses: [
{
id: "a0",
type: "source",
id: 'a0',
type: 'source',
params: {
query: `
SELECT
@@ -419,20 +416,18 @@ describe('aggregation dataview tuned by categories query param', function () {
});
});
describe('Count aggregation', function () {
const mapConfig = {
version: '1.5.0',
layers: [
{
type: "cartodb",
type: 'cartodb',
options: {
source: {
"id": "a0"
id: 'a0'
},
cartocss: "#points { marker-width: 10; marker-fill: red; }",
cartocss_version: "2.3.0"
cartocss: '#points { marker-width: 10; marker-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
@@ -450,8 +445,8 @@ describe('Count aggregation', function () {
},
analyses: [
{
id: "a0",
type: "source",
id: 'a0',
type: 'source',
params: {
query: `
SELECT
@@ -475,7 +470,7 @@ describe('Count aggregation', function () {
]
};
it(`should handle null values correctly when aggregationColumn isn't provided`, function (done) {
it('should handle null values correctly when aggregationColumn isn\'t provided', function (done) {
this.testClient = new TestClient(mapConfig, 1234);
this.testClient.getDataview('categories', { own_filter: 0, categories: 0 }, (err, dataview) => {
assert.ifError(err);
@@ -484,7 +479,7 @@ describe('Count aggregation', function () {
});
});
it(`should handle null values correctly when aggregationColumn is provided`, function (done) {
it('should handle null values correctly when aggregationColumn is provided', function (done) {
mapConfig.dataviews.categories.options.aggregationColumn = 'val';
this.testClient = new TestClient(mapConfig, 1234);
this.testClient.getDataview('categories', { own_filter: 0, categories: 0 }, (err, dataview) => {

View File

@@ -6,9 +6,7 @@ var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
describe('dataview error cases', function () {
describe('generic errors', function () {
afterEach(function (done) {
if (this.testClient) {
this.testClient.drain(done);
@@ -29,23 +27,23 @@ describe('dataview error cases', function() {
version: '1.5.0',
layers: [
{
"type": "cartodb",
"options": {
"source": {
"id": "HEAD"
type: 'cartodb',
options: {
source: {
id: 'HEAD'
},
"cartocss": "#points { marker-width: 10; marker-fill: red; }",
"cartocss_version": "2.3.0"
cartocss: '#points { marker-width: 10; marker-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
dataviews: dataviews,
analyses: [
{
"id": "HEAD",
"type": "source",
"params": {
"query": "select null::geometry the_geom_webmercator, x from generate_series(0,1000) x"
id: 'HEAD',
type: 'source',
params: {
query: 'select null::geometry the_geom_webmercator, x from generate_series(0,1000) x'
}
}
]
@@ -53,7 +51,7 @@ describe('dataview error cases', function() {
}
it('should fail when invalid dataviews object is provided, string case', function (done) {
var mapConfig = createMapConfig("wadus-string");
var mapConfig = createMapConfig('wadus-string');
this.testClient = new TestClient(mapConfig, 1234);
this.testClient.getLayergroup({ response: ERROR_RESPONSE }, function (err, errObj) {
assert.ok(!err, err);
@@ -91,7 +89,6 @@ describe('dataview error cases', function() {
});
describe('pg_typeof', function () {
afterEach(function (done) {
if (this.testClient) {
this.testClient.drain(done);
@@ -112,25 +109,25 @@ describe('dataview error cases', function() {
sql: query,
cartocss: '#layer0 { marker-fill: red; marker-width: 10; }',
cartocss_version: '2.0.1',
source: { id: "a0" }
source: { id: 'a0' }
}
}
],
analyses: [{
id: "a0",
type: "source",
id: 'a0',
type: 'source',
params: {
query: query
}
}],
dataviews: {
aggregation_count_dataview: {
type: "aggregation",
source: { id: "a0" },
type: 'aggregation',
source: { id: 'a0' },
options: {
column: "adm0name",
aggregation: "count",
aggregationColumn: "adm0name"
column: 'adm0name',
aggregation: 'count',
aggregationColumn: 'adm0name'
}
}
}
@@ -210,6 +207,5 @@ describe('dataview error cases', function() {
done();
});
});
});
});

View File

@@ -16,13 +16,13 @@ function createMapConfig(layers, dataviews, analysis) {
function getMapConfig (operation, lastNumber) {
return createMapConfig([
{
"type": "cartodb",
"options": {
"source": {
"id": "a0"
type: 'cartodb',
options: {
source: {
id: 'a0'
},
"cartocss": "#points { marker-width: 10; marker-fill: red; }",
"cartocss_version": "2.3.0"
cartocss: '#points { marker-width: 10; marker-fill: red; }',
cartocss_version: '2.3.0'
}
}
],
@@ -40,8 +40,8 @@ function getMapConfig(operation, lastNumber) {
},
[
{
id: "a0",
type: "source",
id: 'a0',
type: 'source',
params: {
query: `
SELECT

View File

@@ -6,11 +6,11 @@ var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
describe('dataviews using tables without overviews', function () {
var nonOverviewsMapConfig = {
version: '1.5.0',
analyses: [
{ id: 'data-source',
{
id: 'data-source',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
@@ -48,7 +48,7 @@ describe('dataviews using tables without overviews', function() {
]
};
it("should expose a formula", function(done) {
it('should expose a formula', function (done) {
var testClient = new TestClient(nonOverviewsMapConfig);
testClient.getDataview('country_places_count', { own_filter: 0 }, function (err, formula_result, headers) {
if (err) {
@@ -61,9 +61,9 @@ describe('dataviews using tables without overviews', function() {
});
});
it("should admit a bbox", function(done) {
it('should admit a bbox', function (done) {
var params = {
bbox: "-170,-80,170,80"
bbox: '-170,-80,170,80'
};
var testClient = new TestClient(nonOverviewsMapConfig);
testClient.getDataview('country_places_count', params, function (err, formula_result) {
@@ -77,10 +77,8 @@ describe('dataviews using tables without overviews', function() {
});
describe('filters', function () {
describe('category', function () {
it("should expose a filtered formula", function (done) {
it('should expose a filtered formula', function (done) {
var params = {
filters: {
dataviews: { country_categories: { accept: ['CAN'] } }
@@ -96,12 +94,12 @@ describe('dataviews using tables without overviews', function() {
});
});
it("should expose a filtered formula and admit a bbox", function (done) {
it('should expose a filtered formula and admit a bbox', function (done) {
var params = {
filters: {
dataviews: { country_categories: { accept: ['CAN'] } }
},
bbox: "-170,-80,170,80"
bbox: '-170,-80,170,80'
};
var testClient = new TestClient(nonOverviewsMapConfig);
testClient.getDataview('country_places_count', params, function (err, formula_result) {
@@ -113,16 +111,15 @@ describe('dataviews using tables without overviews', function() {
});
});
});
});
});
describe('dataviews using tables with overviews', function () {
var overviewsMapConfig = {
version: '1.5.0',
analyses: [
{ id: 'data-source',
{
id: 'data-source',
type: 'source',
params: {
query: 'select * from test_table_overviews'
@@ -151,7 +148,7 @@ describe('dataviews using tables with overviews', function() {
options: {
column: 'name',
aggregation: 'count',
aggregationColumn: 'name',
aggregationColumn: 'name'
}
},
test_categories_special_values: {
@@ -162,7 +159,7 @@ describe('dataviews using tables with overviews', function() {
options: {
column: 'name',
aggregation: 'sum',
aggregationColumn: 'value',
aggregationColumn: 'value'
}
},
test_histogram: {
@@ -258,19 +255,19 @@ describe('dataviews using tables with overviews', function() {
]
};
it("should expose a sum formula", function(done) {
it('should expose a sum formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_sum', { own_filter: 0 }, function (err, formula_result, headers) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"sum",
"result":15,
"infinities": 0,
"nans": 0,
"nulls":0,
"type":"formula"
operation: 'sum',
result: 15,
infinities: 0,
nans: 0,
nulls: 0,
type: 'formula'
});
assert.ok(getUsesOverviewsFromHeaders(headers)); // Overviews logging
assert(getDataviewTypeFromHeaders(headers) === 'formula'); // Overviews logging
@@ -279,19 +276,19 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose an avg formula", function(done) {
it('should expose an avg formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_avg', { own_filter: 0 }, function (err, formula_result, headers) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"avg",
"result":3,
"nulls":0,
"type":"formula",
"infinities": 0,
"nans": 0
operation: 'avg',
result: 3,
nulls: 0,
type: 'formula',
infinities: 0,
nans: 0
});
assert.ok(getUsesOverviewsFromHeaders(headers)); // Overviews logging
assert(getDataviewTypeFromHeaders(headers) === 'formula'); // Overviews logging
@@ -300,19 +297,19 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose a count formula", function(done) {
it('should expose a count formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_count', { own_filter: 0 }, function (err, formula_result, headers) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"count",
"result":5,
"nulls":0,
"type":"formula",
"infinities": 0,
"nans": 0
operation: 'count',
result: 5,
nulls: 0,
type: 'formula',
infinities: 0,
nans: 0
});
assert.ok(getUsesOverviewsFromHeaders(headers)); // Overviews logging
assert(getDataviewTypeFromHeaders(headers) === 'formula'); // Overviews logging
@@ -321,47 +318,47 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose a max formula", function(done) {
it('should expose a max formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_max', { own_filter: 0 }, function (err, formula_result) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation": "max",
"result": 5,
"nulls": 0,
"infinities": 0,
"nans": 0,
"type": "formula"
operation: 'max',
result: 5,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
testClient.drain(done);
});
});
it("should expose a min formula", function(done) {
it('should expose a min formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_min', { own_filter: 0 }, function (err, formula_result) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation": "min",
"result": 1,
"nulls": 0,
"infinities": 0,
"nans": 0,
"type": "formula"
operation: 'min',
result: 1,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
testClient.drain(done);
});
});
it("should admit a bbox", function(done) {
it('should admit a bbox', function (done) {
var params = {
bbox: "-170,-80,170,80"
bbox: '-170,-80,170,80'
};
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_sum', params, function (err, formula_result) {
@@ -369,19 +366,19 @@ describe('dataviews using tables with overviews', function() {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"sum",
"result":15,
"nulls":0,
"infinities": 0,
"nans": 0,
"type":"formula"
operation: 'sum',
result: 15,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
testClient.drain(done);
});
});
it("should expose a histogram", function (done) {
it('should expose a histogram', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_histogram', function (err, histogram, headers) {
if (err) {
@@ -398,10 +395,8 @@ describe('dataviews using tables with overviews', function() {
});
describe('filters', function () {
describe('histogram', function () {
it("should expose a filtered histogram", function (done) {
it('should expose a filtered histogram', function (done) {
var params = {
filters: {
dataviews: { test_histogram: { min: 2 } }
@@ -421,7 +416,7 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose a filtered histogram with no results", function (done) {
it('should expose a filtered histogram with no results', function (done) {
var params = {
filters: {
dataviews: { test_histogram: { max: -1 } }
@@ -441,7 +436,7 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose a filtered date histogram with no results", function (done) {
it('should expose a filtered date histogram with no results', function (done) {
// This most likely works because the overviews will pass
// the responsibility to the normal dataviews.
var params = {
@@ -465,45 +460,44 @@ describe('dataviews using tables with overviews', function() {
});
describe('category', function () {
var params = {
filters: {
dataviews: { test_categories: { accept: ['Hawai'] } }
}
};
it("should expose a filtered sum formula", function (done) {
it('should expose a filtered sum formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_sum', params, function (err, formula_result, headers) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"sum",
"result":1,
"nulls":0,
"infinities": 0,
"nans": 0,
"type":"formula"
operation: 'sum',
result: 1,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
assert.ok(getUsesOverviewsFromHeaders(headers)); // Overviews logging
testClient.drain(done);
});
});
it("should expose a filtered avg formula", function(done) {
it('should expose a filtered avg formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_avg', params, function (err, formula_result, headers) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"avg",
"result":1,
"nulls":0,
"infinities": 0,
"nans": 0,
"type":"formula"
operation: 'avg',
result: 1,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
assert.ok(getUsesOverviewsFromHeaders(headers)); // Overviews logging
@@ -511,19 +505,19 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose a filtered count formula", function(done) {
it('should expose a filtered count formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_count', params, function (err, formula_result, headers) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"count",
"result":1,
"infinities": 0,
"nans": 0,
"nulls":0,
"type":"formula"
operation: 'count',
result: 1,
infinities: 0,
nans: 0,
nulls: 0,
type: 'formula'
});
assert.ok(getUsesOverviewsFromHeaders(headers)); // Overviews logging
@@ -531,50 +525,50 @@ describe('dataviews using tables with overviews', function() {
});
});
it("should expose a filterd max formula", function(done) {
it('should expose a filterd max formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_max', params, function (err, formula_result) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation": "max",
"result": 1,
"nulls": 0,
"infinities": 0,
"nans": 0,
"type": "formula"
operation: 'max',
result: 1,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
testClient.drain(done);
});
});
it("should expose a filterd min formula", function(done) {
it('should expose a filterd min formula', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_min', params, function (err, formula_result) {
if (err) {
return done(err);
}
assert.deepEqual(formula_result, {
"operation": "min",
"result": 1,
"nulls": 0,
"infinities": 0,
"nans": 0,
"type": "formula"
operation: 'min',
result: 1,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
testClient.drain(done);
});
});
it("should expose a filtered sum formula with bbox", function (done) {
it('should expose a filtered sum formula with bbox', function (done) {
var bboxparams = {
filters: {
dataviews: { test_categories: { accept: ['Hawai'] } }
},
bbox: "-170,-80,170,80"
bbox: '-170,-80,170,80'
};
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_sum', bboxparams, function (err, formula_result) {
@@ -582,24 +576,22 @@ describe('dataviews using tables with overviews', function() {
return done(err);
}
assert.deepEqual(formula_result, {
"operation":"sum",
"result":1,
"nulls":0,
"infinities": 0,
"nans": 0,
"type":"formula"
operation: 'sum',
result: 1,
nulls: 0,
infinities: 0,
nans: 0,
type: 'formula'
});
testClient.drain(done);
});
});
});
describe('aggregation special float values', function () {
var params = {};
it("should expose an aggregation dataview filtering special float values out", function (done) {
it('should expose an aggregation dataview filtering special float values out', function (done) {
var testClient = new TestClient(overviewsMapConfig);
testClient.getDataview('test_categories_special_values', params, function (err, dataview, headers) {
if (err) {

View File

@@ -22,7 +22,6 @@ describe_mvt('date-wrapping', () => {
afterEach(done => testClient.drain(done));
it('should return date columns casted as numbers', done => {
testClient.getTile(0, 0, 0, { format: 'mvt' }, (err, res, mvt) => {
const expected = [
{
@@ -46,15 +45,12 @@ describe_mvt('date-wrapping', () => {
});
it('should return metadata with casted columns', done => {
testClient.getLayergroup(function (err, layergroup) {
assert.ifError(err);
assert.deepEqual(layergroup.metadata.layers[0].meta.dates_as_numbers, ['date']);
done();
});
});
});
describe('and the layer has the "dates_as_numbers" option disabled', () => {
@@ -66,7 +62,6 @@ describe_mvt('date-wrapping', () => {
afterEach(done => testClient.drain(done));
it('should return date columns as dates', done => {
testClient.getTile(0, 0, 0, { format: 'mvt' }, (err, res, mvt) => {
const expected = [
{
@@ -290,7 +285,6 @@ describe_mvt('date-wrapping', () => {
assert.deepEqual(layergroup.metadata.layers[0].meta.dates_as_numbers, ['date']);
done();
});
});
it('should return correct tiles', done => {
@@ -315,5 +309,4 @@ describe_mvt('date-wrapping', () => {
});
});
});
});

View File

@@ -32,8 +32,8 @@ describe('dynamic styling for named maps', function() {
auth: { method: 'open' },
placeholders: {
color: {
type: "css_color",
default: "Reds"
type: 'css_color',
default: 'Reds'
}
},
layergroup: {

View File

@@ -16,10 +16,10 @@ describe('error middleware', function () {
const errorHeader = {
mainError: {
statusCode: 400,
message: "Missing cartocss for layer 0 options",
name: "Error",
label: "ANONYMOUS LAYERGROUP",
type: "layer",
message: 'Missing cartocss for layer 0 options',
name: 'Error',
label: 'ANONYMOUS LAYERGROUP',
type: 'layer'
},
moreErrors: []
};

View File

@@ -11,7 +11,6 @@ describe('error with context', function () {
server = new CartodbWindshaft(serverOptions);
});
var layerOK = {
options: {
sql: 'select cartodb_id, ST_Translate(the_geom_webmercator, 5e6, 0) as the_geom_webmercator ' +

View File

@@ -9,7 +9,6 @@ var CartodbWindshaft = require('../../lib/server');
var serverOptions = require('../../lib/server-options');
describe('health checks', function () {
function enableHealthConfig () {
global.environment.health = {
enabled: true
@@ -57,7 +56,7 @@ describe('health checks', function () {
});
it('error if disabled file exists', function (done) {
var errorMessage = "Maintenance";
var errorMessage = 'Maintenance';
var readFileFn = fs.readFile;
fs.readFile = function (filename, callback) {
@@ -114,5 +113,4 @@ describe('health checks', function () {
done();
});
});
});

View File

@@ -48,7 +48,6 @@ describe('CartoCSS wrap', function () {
]
};
var keysToDelete;
beforeEach(function () {
@@ -61,7 +60,7 @@ describe('CartoCSS wrap', function () {
}
});
it("Label should be text-wrapped", function (done) {
it('Label should be text-wrapped', function (done) {
this.testClient = new TestClient(mapConfig);
this.testClient.getTile(1, 0, 1, { layers: [0] }, (err, res, body) => {
var textWrapPath = './test/fixtures/text_wrap.png';

View File

@@ -25,7 +25,7 @@ describe('layergroup metadata', function () {
{
type: 'cartodb',
options: {
sql: 'select * from populated_places_simple_reduced',
sql: 'select * from populated_places_simple_reduced'
}
}
]

View File

@@ -52,5 +52,4 @@ describe('layers filters', function() {
this.testClient.getTile(0, 0, 0, { layers: layer }, done);
});
});
});

View File

@@ -68,7 +68,7 @@ describe('tests from old api translated to multilayer', function() {
};
}
it("layergroup creation fails if CartoCSS is bogus", function(done) {
it('layergroup creation fails if CartoCSS is bogus', function (done) {
var layergroup = singleLayergroupConfig(wadusSql, '#my_table3{');
assert.response(server,
createRequest(layergroup),
@@ -84,7 +84,7 @@ describe('tests from old api translated to multilayer', function() {
);
});
it("multiple bad styles returns 400 with all errors", function(done) {
it('multiple bad styles returns 400 with all errors', function (done) {
var layergroup = singleLayergroupConfig(wadusSql, '#my_table4{backgxxxxxround-color:#fff;foo:bar}');
assert.response(server,
createRequest(layergroup),
@@ -125,7 +125,7 @@ describe('tests from old api translated to multilayer', function() {
});
// See https://github.com/CartoDB/Windshaft-cartodb/issues/88
it("getting a tile from a user-specific database should return an expected tile", function(done) {
it('getting a tile from a user-specific database should return an expected tile', function (done) {
var layergroup = singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }');
var backupDBHost = global.environment.postgres.host;
@@ -141,7 +141,6 @@ describe('tests from old api translated to multilayer', function() {
assert.ok(parsed.layergroupid);
assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);
keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
keysToDelete['user:cartodb250user:mapviews:global'] = 5;
@@ -152,7 +151,7 @@ describe('tests from old api translated to multilayer', function() {
});
// See https://github.com/CartoDB/Windshaft-cartodb/issues/89
it("getting a tile with a user-specific database password", function(done) {
it('getting a tile with a user-specific database password', function (done) {
var layergroup = singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }');
var backupDBPass = global.environment.postgres_auth_pass;
@@ -177,7 +176,7 @@ describe('tests from old api translated to multilayer', function() {
);
});
it("creating a layergroup from lzma param", function(done){
it('creating a layergroup from lzma param', function (done) {
var params = {
config: JSON.stringify(singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }'))
};
@@ -211,7 +210,7 @@ describe('tests from old api translated to multilayer', function() {
});
});
it("creating a layergroup from lzma param, invalid json input", function(done) {
it('creating a layergroup from lzma param, invalid json input', function (done) {
var params = {
config: 'WADUS'
};
@@ -244,7 +243,7 @@ describe('tests from old api translated to multilayer', function() {
});
});
it("uses queries postgresql to figure affected tables in query", function(done) {
it('uses queries postgresql to figure affected tables in query', function (done) {
var tableName = 'gadm4';
var expectedCacheChannel = _.template('<%= databaseName %>:public.<%= tableName %>', {
databaseName: _.template(global.environment.postgres_auth_user, { user_id: 1 }) + '_db',
@@ -282,7 +281,7 @@ describe('tests from old api translated to multilayer', function() {
});
// https://github.com/CartoDB/cartodb-postgresql/issues/86
it.skip("should not fail with long table names because table name length limit", function(done) {
it.skip('should not fail with long table names because table name length limit', function (done) {
var tableName = 'long_table_name_with_enough_chars_to_break_querytables_function';
var expectedCacheChannel = _.template('<%= databaseName %>:public.<%= tableName %>', {
databaseName: _.template(global.environment.postgres_auth_user, { user_id: 1 }) + '_db',
@@ -316,8 +315,7 @@ describe('tests from old api translated to multilayer', function() {
);
});
it("creates layergroup fails when postgresql queries fail to figure affected tables in query", function(done) {
it('creates layergroup fails when postgresql queries fail to figure affected tables in query', function (done) {
var runQueryFn = PgQueryRunner.prototype.run;
PgQueryRunner.prototype.run = function (username, query, callback) {
return callback(new Error('fake error message'), []);
@@ -342,14 +340,14 @@ describe('tests from old api translated to multilayer', function() {
assert.ok(!res.headers.hasOwnProperty('x-cache-channel'));
var parsed = JSON.parse(res.body);
assert.deepEqual(parsed.errors, ["fake error message"]);
assert.deepEqual(parsed.errors, ['fake error message']);
done();
}
);
});
it("tile requests works when postgresql queries fail to figure affected tables in query", function(done) {
it('tile requests works when postgresql queries fail to figure affected tables in query', function (done) {
var layergroup = singleLayergroupConfig('select * from gadm4', '#gadm4 { marker-fill: red; }');
assert.response(server,
{
@@ -363,7 +361,6 @@ describe('tests from old api translated to multilayer', function() {
status: 200
},
function (res) {
keysToDelete['map_cfg|' + LayergroupToken.parse(JSON.parse(res.body).layergroupid).token] = 0;
keysToDelete['user:localhost:mapviews:global'] = 5;
@@ -402,5 +399,4 @@ describe('tests from old api translated to multilayer', function() {
}
);
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,6 @@ const suites = [
];
describe('mvt regressions', function () {
suites.forEach((suite) => {
const { desc, usePostGIS } = suite;
@@ -123,7 +122,7 @@ describe('MVT Mapnik', function () {
return _.properties.country === 'Sudan';
})[0];
if (!sudanFeature) {
return reject(new Error(`Missing country='Sudan'`));
return reject(new Error('Missing country=\'Sudan\''));
}
resolve(sudanFeature);
@@ -176,5 +175,4 @@ describe('MVT Mapnik', function () {
done();
});
});
});

View File

@@ -10,7 +10,7 @@ function createMapConfig(sql = TestClient.SQL.ONE_POINT) {
return {
version: '1.6.0',
layers: [{
type: "cartodb",
type: 'cartodb',
options: {
sql: sql,
cartocss: TestClient.CARTOCSS.POINTS,
@@ -54,7 +54,7 @@ function mvt(usePostGIS) {
options: {
sql: 'select * from populated_places_simple_reduced limit 10',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0',
cartocss_version: '2.3.0'
}
}]
}
@@ -78,7 +78,6 @@ function mvt(usePostGIS) {
});
describe('analysis-layers-dataviews-mvt', function () {
function createMapConfig (layers, dataviews, analysis) {
return {
version: '1.5.0',
@@ -89,29 +88,29 @@ function mvt(usePostGIS) {
}
var CARTOCSS = [
"#points {",
" marker-fill-opacity: 1.0;",
" marker-line-color: #FFF;",
" marker-line-width: 0.5;",
" marker-line-opacity: 1.0;",
" marker-placement: point;",
" marker-type: ellipse;",
" marker-width: 8;",
" marker-fill: red;",
" marker-allow-overlap: true;",
"}"
'#points {',
' marker-fill-opacity: 1.0;',
' marker-line-color: #FFF;',
' marker-line-width: 0.5;',
' marker-line-opacity: 1.0;',
' marker-placement: point;',
' marker-type: ellipse;',
' marker-width: 8;',
' marker-fill: red;',
' marker-allow-overlap: true;',
'}'
].join('\n');
var mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"source": {
"id": "2570e105-7b37-40d2-bdf4-1af889598745"
type: 'cartodb',
options: {
source: {
id: '2570e105-7b37-40d2-bdf4-1af889598745'
},
"cartocss": CARTOCSS,
"cartocss_version": "2.3.0"
cartocss: CARTOCSS,
cartocss_version: '2.3.0'
}
}
],
@@ -128,10 +127,10 @@ function mvt(usePostGIS) {
},
[
{
"id": "2570e105-7b37-40d2-bdf4-1af889598745",
"type": "source",
"params": {
"query": "select * from populated_places_simple_reduced"
id: '2570e105-7b37-40d2-bdf4-1af889598745',
type: 'source',
params: {
query: 'select * from populated_places_simple_reduced'
}
}
]
@@ -152,10 +151,8 @@ function mvt(usePostGIS) {
testClient.drain(done);
});
});
});
const testCases = [
{
desc: 'should get empty mvt with code 204 (no content)',
@@ -210,11 +207,11 @@ function mvt(usePostGIS) {
const mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"sql": 'SELECT * FROM test_table_overviews',
"cartocss": TestClient.CARTOCSS.POINTS,
"cartocss_version": "2.3.0"
type: 'cartodb',
options: {
sql: 'SELECT * FROM test_table_overviews',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0'
}
}
]
@@ -248,19 +245,19 @@ function mvt(usePostGIS) {
const mapConfig = createMapConfig(
[
{
"type": "cartodb",
"options": {
"sql": 'SELECT * FROM test_table_overviews',
"cartocss": TestClient.CARTOCSS.POINTS,
"cartocss_version": "2.3.0"
type: 'cartodb',
options: {
sql: 'SELECT * FROM test_table_overviews',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0'
}
},
{
"type": "cartodb",
"options": {
"sql": 'SELECT * FROM test_table',
"cartocss": TestClient.CARTOCSS.POINTS,
"cartocss_version": "2.3.0"
type: 'cartodb',
options: {
sql: 'SELECT * FROM test_table',
cartocss: TestClient.CARTOCSS.POINTS,
cartocss_version: '2.3.0'
}
}
]

View File

@@ -45,10 +45,10 @@ describe('named_layers', function() {
auth: {
method: 'open'
},
"placeholders": {
"color": {
"type": "css_color",
"default": "#cc3300"
placeholders: {
color: {
type: 'css_color',
default: '#cc3300'
}
},
layergroup: {
@@ -69,8 +69,8 @@ describe('named_layers', function() {
},
placeholders: {
color: {
"type": "css_color",
"default": "#cc3300"
type: 'css_color',
default: '#cc3300'
}
},
layergroup: {
@@ -80,7 +80,6 @@ describe('named_layers', function() {
}
};
var namedMapLayer = {
type: 'named',
options: {
@@ -199,7 +198,6 @@ describe('named_layers', function() {
});
it('should return 403 if not properly authorized', function (done) {
var layergroup = {
version: '1.3.0',
layers: [
@@ -249,11 +247,9 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should return 200 and layergroup if properly authorized', function (done) {
var layergroup = {
version: '1.3.0',
layers: [
@@ -307,11 +303,9 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should return 400 for nested named map layers', function (done) {
var layergroup = {
version: '1.3.0',
layers: [
@@ -359,11 +353,9 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should return 200 and layergroup with private tables', function (done) {
var privateTableTemplateName = 'private_table_template';
var privateTableTemplate = {
version: '0.0.1',
@@ -483,33 +475,31 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should return 200 and layergroup with private tables and interactivity', function (done) {
var privateTableTemplateNameInteractivity = 'private_table_template_interactivity';
var privateTableTemplate = {
"version": "0.0.1",
"auth": {
"method": "open"
version: '0.0.1',
auth: {
method: 'open'
},
"name": privateTableTemplateNameInteractivity,
"layergroup": {
"layers": [
name: privateTableTemplateNameInteractivity,
layergroup: {
layers: [
{
"type": "cartodb",
"options": {
"attributes": {
"columns": [
"name"
type: 'cartodb',
options: {
attributes: {
columns: [
'name'
],
"id": "cartodb_id"
id: 'cartodb_id'
},
"cartocss": "#layer { marker-fill: #cc3300; }",
"cartocss_version": "2.3.0",
"interactivity": "cartodb_id",
"sql": "select * from test_table_private_1"
cartocss: '#layer { marker-fill: #cc3300; }',
cartocss_version: '2.3.0',
interactivity: 'cartodb_id',
sql: 'select * from test_table_private_1'
}
}
]
@@ -614,11 +604,9 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should return 403 when private table is accessed from non named layer', function (done) {
var layergroup = {
version: '1.3.0',
layers: [
@@ -674,11 +662,9 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should return metadata for named layers', function (done) {
var layergroup = {
version: '1.3.0',
layers: [
@@ -705,8 +691,8 @@ describe('named_layers', function() {
{
type: 'torque',
options: {
sql: "select * from test_table LIMIT 0",
cartocss: "Map { -torque-frame-count:1; -torque-resolution:1; " +
sql: 'select * from test_table LIMIT 0',
cartocss: 'Map { -torque-frame-count:1; -torque-resolution:1; ' +
"-torque-aggregation-function:'count(*)'; -torque-time-attribute:'updated_at'; }"
}
}
@@ -758,11 +744,9 @@ describe('named_layers', function() {
done(err);
}
);
});
it('should work with named tiles', function (done) {
var namedTilesTemplateName = 'named_tiles_template';
var namedTilesTemplate = {
version: '0.0.1',
@@ -873,6 +857,5 @@ describe('named_layers', function() {
done(err);
}
);
});
});

View File

@@ -98,57 +98,57 @@ describe('layers visibility for previews', function() {
var scenarios = [{
name: 'preview_layers_red',
layerPerview: {
'0': true,
'1': false,
'layer2': false
0: true,
1: false,
layer2: false
},
layers: threeLayerPointDistintColor
}, {
name: 'preview_layers_orange',
layerPerview: {
'0': false,
'1': true,
'layer2': false
0: false,
1: true,
layer2: false
},
layers: threeLayerPointDistintColor
}, {
name: 'preview_layers_blue',
layerPerview: {
'0': false,
'1': false,
'layer2': true
0: false,
1: false,
layer2: true
},
layers: threeLayerPointDistintColor
}, {
name: 'preview_layers_red_orange',
layerPerview: {
'0': true,
'1': true,
'layer2': false
0: true,
1: true,
layer2: false
},
layers: threeLayerPointDistintColor
}, {
name: 'preview_layers_red_blue',
layerPerview: {
'0': true,
'1': false,
'layer2': true
0: true,
1: false,
layer2: true
},
layers: threeLayerPointDistintColor
}, {
name: 'preview_layers_orange_blue',
layerPerview: {
'0': false,
'1': true,
'layer2': true
0: false,
1: true,
layer2: true
},
layers: threeLayerPointDistintColor
}, {
name: 'preview_layers_red_orange_blue',
layerPerview: {
'0': true,
'1': true,
'layer2': true
0: true,
1: true,
layer2: true
},
layers: threeLayerPointDistintColor
}, {
@@ -213,5 +213,4 @@ describe('layers visibility for previews', function() {
);
});
});
});

Some files were not shown because too many files have changed in this diff Show More