Skip to content

Instantly share code, notes, and snippets.

@adnan-i
Created December 29, 2017 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adnan-i/53c95dbc0f732aa83fe04f4c1d5218fc to your computer and use it in GitHub Desktop.
Save adnan-i/53c95dbc0f732aa83fe04f4c1d5218fc to your computer and use it in GitHub Desktop.
Excerpt from a service that constructs a complex SQL-GIS query
/*
* Whenever possible try and construct all the queries by using the ORM API.
* Manually written queries are susceptible to SQL-injections
*/
_getClosestQuery(params) {
const seq = this.Model.sequelize;
const point = seq.fn('ST_MakePoint', ...params.point.coordinates);
const srid = seq.fn('ST_SetSRID', point, 4326);
const stDistanceSphere = seq.fn('ST_DISTANCE_SPHERE', seq.col('point'), srid);
const query = {
attributes: {
include: [[stDistanceSphere, 'distance']]
},
include: [{model: this.server.plugins.users.User.scope('canReceiveOffers'), required: true}],
order: [[stDistanceSphere, 'ASC']],
};
if (params.limit) {
query.limit = params.limit;
}
if (_.isObject(params.where)) {
query.where = _.assign(query.where, params.where);
}
return query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment