Skip to content

Commit

Permalink
fix: add validator to positions.point
Browse files Browse the repository at this point in the history
  • Loading branch information
fufeck committed Nov 13, 2024
1 parent 4f20132 commit b1323de
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
3 changes: 3 additions & 0 deletions libs/shared/src/entities/position.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
import { Numero } from './numero.entity';
import { Toponyme } from './toponyme.entity';
import { ObjectId } from 'mongodb';
import { Validate } from 'class-validator';
import { PointValidator } from '../validators/coord.validator';

export enum PositionTypeEnum {
ENTREE = 'entrée',
Expand Down Expand Up @@ -64,6 +66,7 @@ export class Position {

@Index('IDX_positions_point', { spatial: true })
@ApiProperty()
@Validate(PointValidator)
@Column('geometry', {
nullable: false,
spatialFeatureType: 'Point',
Expand Down
30 changes: 17 additions & 13 deletions libs/shared/src/validators/coord.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import {
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import * as proj from '@etalab/project-legal';
import { getLabel, readValue } from '@ban-team/validateur-bal';
import { Point } from '@turf/turf';

async function validateurBAL(value, label) {
const { errors } = await readValue(label, value);
Expand All @@ -12,22 +14,24 @@ async function validateurBAL(value, label) {
};
}

function harmlessProj(coordinates: number[]) {
try {
return proj(coordinates);
} catch {}
}

@ValidatorConstraint({ name: 'pointCoord', async: true })
export class PointValidator implements ValidatorConstraintInterface {
async validate(coordinates: any) {
if (Array.isArray(coordinates) && coordinates.length === 2) {
const [lat, long] = coordinates;
if (typeof lat !== 'number' || typeof long !== 'number') {
async validate(point: Point) {
if (Array.isArray(point.coordinates) && point.coordinates.length === 2) {
if (
typeof point.coordinates[0] !== 'number' ||
typeof point.coordinates[0] !== 'number'
) {
return false;
}

const latResults = await validateurBAL(lat.toString(), 'lat');
if (latResults.errors.length > 0) {
return false;
}

const longResults = await validateurBAL(long.toString(), 'long');
if (longResults.errors.length > 0) {
const projectedCoordInMeters = harmlessProj(point.coordinates);
if (!projectedCoordInMeters) {
return false;
}
} else {
Expand All @@ -38,7 +42,7 @@ export class PointValidator implements ValidatorConstraintInterface {
}

defaultMessage() {
return 'Les coordonnées du point ne sont pas valide';
return " Les coordonnées du point ne sont pas valides. Contactez nous sur [email protected] avec l'objet 'Mauvaise positions' pour nous aider à corriger le bug";
}
}

Expand Down

0 comments on commit b1323de

Please sign in to comment.