# Usage Guidelines for Node.js Client Libraries

This document shows you how to use the Enfonica client libraries in a Node.js environment, including how to import the libraries, creating and closing a client instance and recommendations when calling API methods. Examples will use the [@enfonica/messaging](https://www.npmjs.com/package/@enfonica/messaging) node module. 

The Enfonica Node.js client libraries use google-gax[^1] as its transport layer and are heavily inspired by Google Cloud TypeScript libraries. The client libraries are generated using Google Cloud API tooling and use gRPC under the hood.

## Importing the library

JavaScript:
```js
const messaging = require('@enfonica/messaging');
```

TypeScript:
```ts
import * as messaging from '@enfonica/messaging';
```

## Managing the API client

Initialize a client instance:
```ts
const messagesClient = new messaging.MessagesClient();
```

We recommend you create the client instance once and reuse it rather than creating a new client instance for every API call. This will greatly improve the performance of API calls.

If the instance is no longer required, you should call `close()`. If you take the recommended approach and reuse the client for the lifetime of your application, you do not need to call `close()`.
```ts
messagesClient.close();
```

## Calling API methods

We recommended client methods be used with `async` / `await`:
```ts
const [response] = await messagesClient.getMessage(request);
```

## Auto-pagination

We recommend using the `*Async` list methods when you require paging. These methods return an asynchronous iterator that can be iterated using a `for await` loop. For example, if you need a list of messages you can use `listMessagesAsync` which can be used like this:
```ts
const iterable = messagesClient.listMessagesAsync(request);
for await (const response of iterable) {
  // process response
}
```

[^1]:
    [gax-nodejs - Client Libraries "How To"](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md)
