Is there a way to define type information for a global variable when utilizing dynamic import within a function?

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?

Answer №1

If you import the type alone and restrict its usage to type definitions, it will not be loaded in the compiled JavaScript code:

import { androidpublisher_v3 } from "googleapis";
let androidpublisher: androidpublisher_v3 | undefined;

To prevent accidental referencing in value expressions, consider using import types:

let androidpublisher: import("googleapis").androidpublisher_v3 | undefined;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Convert a Java library to JavaScript using JSweet and integrate it into an Angular project

Just recently, I embarked on my journey to learn TypeScript. To challenge my newfound knowledge, I was tasked with transpiling a Java library using JSweet in order to integrate it into an Angular project. This specific Java library is self-contained, consi ...

Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page. The initial URL looks like this: localhost:3000/?page=1&genres=tree But upon refres ...

Calculator for calculating values using JavaScript data attributes

One issue is that certain elements are canceling each other out.. The value of the element is specified in the "data-price" attribute. My code is currently not valid and does not handle it properly, ideally I would like to update the total whenever a selec ...

Execute a zoom out action by pressing the (Ctrl) and (-) keys simultaneously in Javascript

I'm trying to figure out how to simulate a Ctrl - zoom out using Javascript. I've noticed that using the style zoom property or the transform property gives different results with white space in the corners, rather than the smooth zoom out effect ...

Problem importing npm module with Meteor 1.3

I've been trying to follow the guide for using npm packages in Meteor 1.3, particularly focusing on installing the moment npm module. However, I can't seem to work it out despite its simplicity. Every time I attempt to use the package in the cli ...

Looking to retrieve CloudWatch logs from multiple AWS accounts using Lambda and the AWS SDK

Seeking guidance on querying CloudWatch logs across accounts using lambda and AWS SDK Developing a lambda function in typescript Deploying lambda with CloudFormation, granting necessary roles for reading from two different AWS accounts Initial exe ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

What is the best way to transfer a table row from one table to another in AngularJS?

I need assistance with a feature that allows users to move rows between tables by clicking on buttons. When the 'up' button is clicked, the 2nd table row should be moved to the 1st table, and when the 'down' button is clicked, the 1st t ...

Convert numerical values to currency format

Here is a number 5850 that I would like to format as currency. Format Example 1: 5850 => $58.50 Format Example 2: 9280 => $92.80 I am utilizing the function below: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparat ...

Using a datepicker to calculate dates within a computed function in Vue

I'm currently exploring the most efficient method to dynamically generate fields based on date count or display a default option. Currently, I have successfully implemented the default setting of 11 days. However, my goal is to calculate the differen ...

The functionality of TypeScript's instanceof operator may fail when the method argument is not a simple object

There seems to be an issue with a method that is being called from two different places but returns false for both argument types. Despite checking for the correct types, the problem persists and I am unsure why. Although I have read a similar question on ...

What are the steps to approve an Amazon Pay request for retrieving a "get checkout session"?

Exploring the integration of Amazon pay as a payment option for customers on my website has led me to encounter some challenges with understanding the request headers required for calling the Amazon Pay API. Attempting a request to 'https://pay-api.a ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

How to send a DOM element's value to an AJAX request using HTML.PagedList parameters

As I delve into learning ajax requests, I find myself questioning if I am on the right track. Currently, I have a page that incorporates pagination, sorting, and searching functionalities. My goal is to implement these features using ajax to avoid reloadin ...

checkbox with an option tag

I need help with implementing multi-select checkboxes inside an Angular 4 application. The checkboxes are not appearing next to the team names as intended. Can anyone assist me with this issue? Below is a snippet of my HTML code: <select class="form-c ...

In Typescript 2.2, when using Express, the request and response objects are implicitly

I'm facing some challenges when it comes to incorporating types into my node/express project. Currently, I am using TypeScript 2.2 and express 4.x with the following npm installation for types: npm install --save-dev @types/express import * as expr ...

Unique custom CSS and meta tag options for enhancing iPad/iPhone user experience

Currently, I am developing a web application that integrates Extjs components, PHP, and MySQL. My main goal is to ensure that my application looks correct on the iPad. Are there any specific CSS rules or meta tags that I should be implementing for optima ...

invoke a pop-up window from a separate document

How can I make a modal window open from another file? I can't seem to figure out why it's not working. file 1: <template> <section class="header"> <div class="header-container"> <div cl ...

Steps for inserting a video into a new div upon selecting a hyperlink

Looking for a way to link menu elements to corresponding videos in adjacent divs? I have two divs set up - one with the menu list and another right next to it where the videos should be loaded. Forms seem like a potential solution, but I lack expertise i ...