LoopBack 4 Todo Application Tutorial - Integrate with a geo-coding service
Services
To call other APIs and web services from LoopBack applications, we recommend touse Service Proxies as a design pattern for encapsulating low-levelimplementation details of communication with 3rd-party services and providingJavaScript/TypeScript API that’s easy to consume e.g. from Controllers. SeeCalling other APIs and web servicesfor more details.
In LoopBack, each service proxy is backed by aDataSource, this datasource leverages one ofthe service connectors to make outgoing requests and parse responses returned bythe service.
In our tutorial, we will leverageUS Census Geocoder API to converttextual US addresses into GPS coordinates, thus enabling client applications ofour Todo API to display location-based reminders,
Tip: In a real project, you may want to use a geocoding service that covers morecountries beyond USA and provides faster responses than US Census Geocoder API,for example IBM’s Weather Company Dataor Google Maps Platform.
Configure the backing datasource
Run lb4 datasource
to define a new datasource connecting to Geocoder RESTservice. When prompted for a connector to use, select “REST services”.
$ lb4 datasource
? Datasource name: geocoder
? Select the connector for geocoder: REST services (supported by StrongLoop)
? Base URL for the REST service:
? Default options for the request:
? An array of operation templates:
? Use default CRUD mapping: No
create src/datasources/geocoder.datasource.json
create src/datasources/geocoder.datasource.ts
# npm will install dependencies now
update src/datasources/index.ts
Datasource Geocoder was created in src/datasources/
Edit the newly created datasource configuration to configure Geocoder APIendpoints. Configuration options provided by REST Connector are described in ourdocs here: REST connector.
/src/datasources/geocoder.datasource.json
{
"connector": "rest",
"options": {
"headers": {
"accept": "application/json",
"content-type": "application/json"
}
},
"operations": [
{
"template": {
"method": "GET",
"url": "https://geocoding.geo.census.gov/geocoder/locations/onelineaddress",
"query": {
"format": "{format=json}",
"benchmark": "Public_AR_Current",
"address": "{address}"
},
"responsePath": "$.result.addressMatches[*].coordinates"
},
"functions": {
"geocode": ["address"]
}
}
]
}
Implement a service provider
Create a new directory src/services
and add the following two new files:
src/services/geocoder.service.ts
defining TypeScript interfaces for Geocoderservice and implementing a service proxy provider.src/services/index.ts
providing a conventient access to all services via asingleimport
statement.
src/services/geocoder.service.ts
import {getService, juggler} from '@loopback/service-proxy';
import {inject, Provider} from '@loopback/core';
import {GeocoderDataSource} from '../datasources/geocoder.datasource';
export interface GeoPoint {
/**
* latitude
*/
y: number;
/**
* longitude
*/
x: number;
}
export interface GeocoderService {
geocode(address: string): Promise<GeoPoint[]>;
}
export class GeocoderServiceProvider implements Provider<GeocoderService> {
constructor(
@inject('datasources.geocoder')
protected dataSource: juggler.DataSource = new GeocoderDataSource(),
) {}
value(): Promise<GeocoderService> {
return getService(this.dataSource);
}
}
src/services/index.ts
export * from './geocoder.service';
Enhance Todo model with location data
Add two new properties to our Todo model: remindAtAddress
and remindAtGeo
.
src/models/todo.model.ts
@model()
export class Todo extends Entity {
// original code remains unchanged, add the following two properties:
@property({
type: 'string',
})
remindAtAddress?: string; // address,city,zipcode
@property({
type: 'string',
})
remindAtGeo?: string; // latitude,longitude
}
Look up address location in the controller
Finally, modify TodoController
to look up the address and convert it to GPScoordinates when a new Todo item is created.
Import GeocodeService
interface into the TodoController
and then modify theController constructor to receive GeocodeService
as a new dependency.
src/controllers/todo.controller.ts
import {inject} from '@loopback/core';
import {GeocoderService} from '../services';
export class TodoController {
constructor(
@repository(TodoRepository) protected todoRepo: TodoRepository,
@inject('services.GeocoderService') protected geoService: GeocoderService,
) {}
// etc.
}
Modify createTodo
method to look up the address provided in remindAtAddress
property and convert it to GPS coordinates stored in remindAtGeo
.
src/controllers/todo.controller.ts
export class TodoController {
// constructor, etc.
@post('/todos')
async createTodo(@requestBody() todo: Todo) {
if (!todo.title) {
throw new HttpErrors.BadRequest('title is required');
}
if (todo.remindAtAddress) {
// TODO handle "address not found"
const geo = await this.geoService.geocode(todo.remindAtAddress);
// Encode the coordinates as "lat,lng"
todo.remindAtGeo = `${geo[0].y},${geo[0].x}`;
}
return this.todoRepo.create(todo);
}
// other endpoints remain unchanged
}
Congratulations! Now your Todo API makes it easy to enter an address for areminder and have the client application show the reminder when the devicereaches close proximity of that address based on GPS location.
Navigation
Previous step: Putting it all together