Here is a simplified version of my server code:
server.ts
import google from "googleapis";
const androidPublisher = google.androidpublisher("v3");
app.use('something', function(req, res, n){
...
})
...(only one of the dozens of other methods use androidPublisher)
In my serverless environment (firebase functions), importing the googleapis
library to set up the androidpublisher
variable adds significant latency ranging from 400ms to 700ms, compared to only 10ms to 30ms for other library files.
Considering that only about 1 out of every 100 requests actually require the use of androidPublisher
, I decided to leverage dynamic import to only load googleapis
when necessary. This way, I can avoid adding unnecessary latency to all requests that initiate new serverless instances due to initializing androidPublisher
.
To achieve this optimization, I made the following modifications:
server.ts
let androidPublisherInstance:any;
async function getAndroidPublisher() {
const googleapis = await import("googleapis");
if (androidPublisherInstance === undefined) {
const ap = googleapis.google.androidpublisher("v3");
androidPublisherInstance = ap;
}
return androidPublisherInstance;
}
...(one of methods utilize getAndroidPublisher() to obtain the androidPublisher instance)
With this updated setup, where I utilize a global variable and a helper function to initialize androidPublisher
only when needed, I successfully managed to eliminate the initial 400ms~700ms latency when androidPublisher
is required. However, I encountered difficulties defining the type of androidPublisherInstance
correctly since the type definition exists within the googleapis
module contained inside the getAndroidPublisher
function.
As a result, I lose the advantages of using TypeScript and must resort to guesswork when utilizing methods/properties associated with androidPublisherInstance
.
I feel compelled to use a global variable because I want to prevent multiple initializations of androidPublisher
each time a function invokes getAndroidPublisher()
.
Am I overlooking a solution? Is there a method to employ dynamic import and ensure that the client is initialized only once without necessitating the use of a global variable?