I have a location entity holding coordinates. Based on a radius I want to get all locations that are within range.
I created a function (backend code / Nestjs logic, not database) calculating the distance between two locations. If the calculated distance is smaller than or equal to the radius I want to select this location.
My current repository implementation using this distance calculation function:
// ...
import { distanceFromCoordinatesInKilometers } from '../shared/calculations/distanceFromCoordinatesInKilometers';
@EntityRepository(Location)
export class LocationsRepository extends Repository<Location> {
public getLocations({ /* ... */ latitude, longitude, radiusInKilometers }: GetLocationsDTO): Promise<Location[]> {
const query: SelectQueryBuilder<Location> = this.createQueryBuilder('location');
// ....
if(latitude && longitude && radiusInKilometers) {
query.andWhere("distanceFromCoordinatesInKilometers(location.latitude, location.longitude, :latitude, :longitude) <= :radiusInKilometers", {
latitude,
longitude,
radiusInKilometers,
});
}
return query.getMany();
}
}
The example shown above doesn't work. I get this error
QueryFailedError: function distanceFromCoordinatesInKilometers(double precision, double precision, unknown, unknown) does not exist
When adding a :
to the function I get this error
Function parameter isn't supported in the parameters. Please check "distance" parameter.
How would I call my backend code function distanceFromCoordinatesInKilometers
within that query? I can pass in variables but not functions?
Currently I'm using a Postgres database but it would be awesome if there is an independent solution.
node.js
app from the database, that's never gonna work, an universal solution would be to: implement that function in the database (eg. by migrations), or more driver-agnostic solution: implement that function in your query