Integrate Node.js Client for Google Maps Services With a NestJS Application | by Marcus Castanho | Jan, 2022

Encapsulating the NodeJS Client for Google Map Services in NestJS

Marcos Castanho
Photo by TH Chia on Unsplash

NestJS is a file A framework for building scalable and loosely associable server-side NodeJS applications. One of its main characteristics is the implemented architecture and directory structure, which reinforces the modular nature of the application. Furthermore, NestJS fully supports TypeScript and also works with Express and Fastify under the hood, making it an up-to-date and viable alternative framework for building a reliable web server with well-known tools.

As mentioned in the NestJS documentation, its architecture is heavily inspired by Angular architecture. The folder structure is basically organized into modules that represent some entity that binds to a specific context of the application. Each unit generally consists of files app.module.tsAnd app.controller.ts, And app.service.ts. The module’s global folder structure looks like this:

google-maps
| — google-maps.controller.ts
| — google-maps.module.ts
| — google-maps.service.ts

The Google Maps service client is a library built to interact with a web API provided by Google directly from a specific project’s programming language, in this case, TypeScript with NodeJS.

the google-maps The module folder simply consists of a file module.ts ts file and file, which contains the client getter and other frequently used methods. The service will then look like this:

  • In the builder method, the Client It is instantiated and the access key is retrieved from an environment variable for security reasons, using the built-in NestJS service ConfigService;
  • Getters operations are defined so that new instances of . are selected GoogleMapsService The class can access Client example and accessKey;
  • In this example, an asynchronous method is called getCoordinates It is defined to get the latitude and longitude values ​​from a given address using a .geocode method that communicates with the web service’s API;
  • Since the application uses TypeScript, the package also provides custom types for the library so that the returned value type of the generated method can be specified as LatLngLiteral.

Finally, the created google maps module needs to be declared inside the module using google maps service and then using dependency injection in the class using google maps service methods. Other modules might look like this:

As discussed before, it is interesting to write code in a modular way in scalable applications with multiple entity scopes.

Leave a Comment