actions-on-google / actions-on-google-nodejs

Node.js client library for Actions on Google
https://actions-on-google.github.io/actions-on-google-nodejs
Apache License 2.0
900 stars 197 forks source link

Smart Home: Cache authorization tokens #423

Open bramkragten opened 3 years ago

bramkragten commented 3 years ago

Closes #421

For every requestSync or reportState request, a new JWTClient is created, causing a post request to get a new token: https://github.com/actions-on-google/actions-on-google-nodejs/blob/eaa9e2058273dd7832031e1d8496e134ba60f791/src/service/smarthome/smarthome.ts#L332

The token that is returned is valid for an hour, but the client and token are still recreated for every request.

With this PR, the JWTClient is created just once, on first use, this causes that the token is cached and only refreshed when it is no longer valid.

Furthermore, during the request of a new token, all other requests now wait for this token to finish loading instead of starting a new load.

This will drastically improve the performance and lower the number of requests to the Google Authentication API.

(Sorry, prettier doesn't seem agree with your style guidelines)