Skip to content

Commit

Permalink
COMPENF-648-Changed location parameters from param types to query typ…
Browse files Browse the repository at this point in the history
…es (#115)
  • Loading branch information
barrfalk authored Aug 23, 2023
1 parent de86cc1 commit 699cd01
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 44 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Controller, Get, Param } from '@nestjs/common';
import { Controller, Get, Query } from '@nestjs/common';
import { BcGeoCoderService } from './bc_geo_coder.service';
import { Roles } from '../../auth/decorators/roles.decorator';
import { Role } from '../../enum/role.enum';
Expand All @@ -7,10 +7,10 @@ import { Role } from '../../enum/role.enum';
export class BcGeoCoderController {
constructor(private readonly bcGeoCoderService: BcGeoCoderService) {}

@Get('/address/:query')
@Get('/address')
@Roles(Role.COS_OFFICER)
findAll(@Param('query') query: string) {
return this.bcGeoCoderService.findAll(query);
findAll(@Query('localityName') localityName?: string, @Query('addressString') addressString?: string) {
return this.bcGeoCoderService.findAll(localityName,addressString);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe("BcGeoCoderService", () => {

jest.spyOn(httpService, 'get').mockReturnValue(of(mockResponse));
const features: Feature = await service.findAll(
"2975 Jutland Road, Victoria, BC"
"Victoria","2975 Jutland Road"
);

expect(features.features[0].geometry.coordinates).toEqual(mockCoordinates);
Expand Down
60 changes: 37 additions & 23 deletions backend/src/external_api/bc_geo_coder/bc_geo_coder.service.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,44 @@
import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { catchError, firstValueFrom } from 'rxjs';
import { AxiosError} from 'axios';
import { Feature } from 'src/types/bc_geocoder/bcGeocoderType';
import { Injectable, Logger } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import { catchError, firstValueFrom } from "rxjs";
import { AxiosError } from "axios";
import { Feature } from "src/types/bc_geocoder/bcGeocoderType";

@Injectable()
export class BcGeoCoderService {
private readonly logger = new Logger(BcGeoCoderService.name);

private readonly logger = new Logger(BcGeoCoderService.name);

constructor(private readonly httpService: HttpService) {}

async findAll(query: string): Promise<Feature> {
const maxResults = 10;
const apiUrl = `${process.env.BC_GEOCODER_API_URL}/addresses.json?addressString=${query}&locationDescriptor=any&maxResults=${maxResults}&interpolation=adaptive&echo=true&brief=false&autoComplete=true&setBack=0&outputSRS=4326&minScore=2&provinceCode=BC`;

const { data } = await firstValueFrom(
this.httpService.get<any>(apiUrl).pipe(
catchError((error: AxiosError) => {
this.logger.error(error.response.data);
throw 'Error getting BC Geocoder response';
}),
),
);
return data;
constructor(private readonly httpService: HttpService) {}

// given a localityName (community, for example) and an address, return the Feature given by BC Geocoder
async findAll(localityName: string, addressString: string): Promise<Feature> {
const maxResults = 10;
let apiUrl: string;
this.logger.debug(
`Calling BC Geocoder. Parameters sent to backend were localityName: ${localityName} and addressString: ${addressString}`
);
if (addressString && localityName) {
this.logger.debug(
`Calling BC Geocoder with address ${addressString} and community ${localityName}`
);
apiUrl = `${process.env.BC_GEOCODER_API_URL}/addresses.json?addressString=${addressString}&locationDescriptor=any&maxResults=${maxResults}&interpolation=adaptive&echo=true&brief=false&autoComplete=true&setBack=0&outputSRS=4326&minScore=2&localityName=${localityName}&provinceCode=BC`;
} else if (localityName) {
this.logger.debug(`Calling BC Geocoder with community ${localityName}`);
apiUrl = `${process.env.BC_GEOCODER_API_URL}/addresses.json?locationDescriptor=any&maxResults=${maxResults}&interpolation=adaptive&echo=true&brief=false&autoComplete=true&setBack=0&outputSRS=4326&minScore=2&localityName=${localityName}&provinceCode=BC`;
} else if (addressString && addressString.length > 0) {
this.logger.debug(`Calling BC Geocoder with address ${addressString}`);
apiUrl = `${process.env.BC_GEOCODER_API_URL}/addresses.json?addressString=${addressString}&locationDescriptor=any&maxResults=${maxResults}&interpolation=adaptive&echo=true&brief=false&autoComplete=true&setBack=0&outputSRS=4326&minScore=2&provinceCode=BC`;
}

if (apiUrl) {
const { data } = await firstValueFrom(
this.httpService.get<any>(apiUrl).pipe(
catchError((error: AxiosError) => {
this.logger.error(error.response);
throw "Error getting BC Geocoder response";
})
)
);
return data;
}
}
}
10 changes: 5 additions & 5 deletions frontend/src/app/components/common/bc-geocoder-autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { FC, useEffect, useState } from "react";
import CreatableSelect from "react-select/creatable";
import { useAppDispatch, useAppSelector } from "../../hooks/hooks";
import {
getComplaintLocation,
getComplaintLocationByAddress,
selectComplaintLocation,
} from "../../store/reducers/complaints";

Expand Down Expand Up @@ -37,7 +37,7 @@ export const BCGeocoderAutocomplete: FC<Props> = ({

useEffect(() => {
const fetchAddresses = async (inputValue: string) => {
dispatch(getComplaintLocation(`${inputValue}`));
dispatch(getComplaintLocationByAddress(inputValue));

try {
if (complaintLocation) {
Expand All @@ -49,15 +49,15 @@ export const BCGeocoderAutocomplete: FC<Props> = ({
if (options) {
setAddressOptions(options);
}
} else {
console.log("Feature length 0");
}
}
} catch (error) {
console.error("Error fetching addresses:", error);
}
};
fetchAddresses(inputValue);
if (inputValue) {
fetchAddresses(inputValue);
}
}, [inputValue, maxResults]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ export const ComplaintLocation: FC<Props> = ({ complaintType, draggable }) => {
lat = +coordinates[0];
lng = +coordinates[1];
} else if (complaintLocation) {
lat = complaintLocation?.features[0].geometry.coordinates[1];
lng = complaintLocation?.features[0].geometry.coordinates[0];
lat = complaintLocation?.features[0].geometry?.coordinates[1];
lng = complaintLocation?.features[0].geometry?.coordinates[0];
}
return (
<div className="comp-complaint-details-location-block">
Expand Down
34 changes: 25 additions & 9 deletions frontend/src/app/store/reducers/complaints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,7 @@ export const getWildlifeComplaintByComplaintIdentifier =
location_summary_text,
cos_geo_org_unit: { area_name },
} = ceComplaint;

dispatch(
getComplaintLocation(`${location_summary_text ?? ""} ${area_name}`)
);
dispatch(getComplaintLocation(area_name, location_summary_text));
}

dispatch(setComplaint({ ...response }));
Expand Down Expand Up @@ -258,9 +255,7 @@ export const getAllegationComplaintByComplaintIdentifier =
cos_geo_org_unit: { area_name },
} = ceComplaint;

dispatch(
getComplaintLocation(`${location_summary_text ?? ""} ${area_name}`)
);
dispatch(getComplaintLocation(area_name, location_summary_text));
}

dispatch(setComplaint({ ...response }));
Expand Down Expand Up @@ -293,14 +288,35 @@ export const getZoneAtAGlanceStats =
}
};

export const getComplaintLocation =
export const getComplaintLocationByAddress =
(address: string): AppThunk =>
async (dispatch) => {
try {
const parameters = generateApiParameters(
`${config.API_BASE_URL}/bc-geo-coder/address/${address}`
`${config.API_BASE_URL}/bc-geo-coder/address?addressString=${address}`
);
const response = await get<Feature>(dispatch, parameters);
dispatch(setComplaintLocation(response));
} catch (error) {
//-- handle the error message
}
};

export const getComplaintLocation =
(area: string, address?: string): AppThunk =>
async (dispatch) => {
try {
let parameters;

if (address && area) {
parameters = generateApiParameters(
`${config.API_BASE_URL}/bc-geo-coder/address?localityName=${area}&addressString=${address}`
);
} else {
parameters = generateApiParameters(
`${config.API_BASE_URL}/bc-geo-coder/address?localityName=${area}`
);
}
const response = await get<Feature>(dispatch, parameters);
dispatch(setComplaintLocation(response));
} catch (error) {
Expand Down

0 comments on commit 699cd01

Please sign in to comment.