Created
December 29, 2017 12:47
-
-
Save adnan-i/53c95dbc0f732aa83fe04f4c1d5218fc to your computer and use it in GitHub Desktop.
Excerpt from a service that constructs a complex SQL-GIS query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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