What is the best way to establish a connection to Redis within one of my cloud functions?

I have multiple cloud functions organized in the following file structure:

root
 |_ functions
        |___src
             |___services
             |       |___function1.ts
             |       |___function2.ts
             |       |___function3.ts
             |
             |___index.tx

In the index file, I import all the functions and export them for use in the cloud functions:

//index.ts

const function1 = require(./services/function1)
const function2 = require(./services/function2)
const function3 = require(./services/function3)

exports.function1 = function1.function1
exports.function2 = function2.function2
exports.function3 = function3.function3

However, only function1 requires the use of redis. Here is my redis.ts file:

import * as redis from "redis";

const REDISHOST = process.env.REDISHOST || 'localhost';
const REDISPORT = Number(process.env.REDISPORT || 6379);

const redisClient = redis.createClient({
  socket: {
    host: REDISHOST,
    port: REDISPORT,
  },
});
redisClient.on('error', err => console.error('ERR:REDIS:', err));
redisClient.connect();

export default redisClient;

This redis client is then imported into function1 as shown below:

import redisClient from "../common/redis"

exports.function1 = onRequest(logic)

The issue arises when deploying function2 and function3, as they also attempt to connect to redis even though the redis client is not imported into them. What could be the mistake in this setup?

Answer №1

One important thing to keep in mind is that each time a function is exported from your index.ts file, the entire file is executed. This means that on a fresh start of a new server instance, every function will:

  1. require ./services/function1
  2. import redis.ts
  3. create an instance of the redisClient globally

A better approach would be not to declare redisClient as a global variable that is created whenever the module loads. Instead, delay its creation until it is actually needed within the function, and then cache it globally if necessary, making it available for future function calls on the same server instance.

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

Best Practices for Error Handling in Typescript

After delving into articles about error handling, a thought lingers in my mind - is throwing an exception on validation logic in the value object really the most efficient approach? Take for example this class that represents a value object: export class U ...

Ways to conceal button for inactive edit row on a table

I am trying to implement inline editing for a table in my application. The requirement is to hide the "Edit" and "Delete" buttons for all other rows when the user clicks on the edit button of a particular row. I have attempted to achieve this using the c ...

While the file does exist in the current directory, the `readFileSync` function is unable to locate

For my latest SvelteKit project, I was developing a Joke API using Bun as the runtime and TypeScript as the programming language. The goal of this API was to fetch one random dad joke from a text file that contained 363 jokes. Everything was going smoothly ...

Using whereToEqual on a sub-object array containing an unknown field: a comprehensive guide

Here is the Firestore document structure for you to view. https://i.sstatic.net/TOFH1.png I need assistance with comparing values in the array stops because the time 12:00 PM varies for each departure entry. My goal is to retrieve the value of buss wher ...

Using React's useState with WebSocket is causing the array to fail to update properly

Greetings, I am currently working on integrating WebSockets with react, and possibly electron as well. When the connection opens, the message 'Connection opened' is correctly added to the beginning of a new array and displayed as expected. Howe ...

Using useState as props in typescript

Let's imagine a situation where I have a main component with two smaller components: const MainComponent = () => { const [myValue, setMyValue] = useState(false) return ( <> <ChildComponent1 value={myValue} setValue={set ...

Exploring the power of Typescript alongside Styled Components and Material UI

Working with Typescript in conjunction with MUI and Styled-Components may lead to the need to pass props directly to MUI elements to address type errors... const Index = () => { return ( <StyledButton variant="contained" > ...

"Combining the power of VueJs with the versatility

Currently, I'm delving into the world of VueJS alongside Firebase (and VueFire), and I've hit a bit of a snag when it comes to organizing my data effectively. My scenario is rather straightforward. I have a database of suppliers and a database ...

Is there a way to specify this component without it being nested within the parent element?

So I have this component nested within another one const selectColumn = useMemo<ColumnDef<Person>[]>( () => [ { id: "select", header: ({ table }) => ( <IndeterminateCheckbox {.. ...

Adding a record to a multi-dimensional array in TypeScript, for example with an Array of numbers, pairs of numbers, and pairs of strings and numbers

In my angular component file, I am utilizing 'angular-highcharts' to create a high chart for the HTML view page. To do this, I have defined an array as shown below in the component.ts file to store and organize the data. public myData : Array< ...

Troubleshooting issue in Typescript with useFieldArray relating to property name

I am encountering an issue with useFieldArray in TypeScript. The problem arises when trying to specify the controller's name as: name={test.${index}.firstname} The error message reads: controller.d.ts(18, 5): The expected type comes from property &ap ...

Dependency management with various versions of an NPM package

I'm feeling a bit puzzled about NPM package versions. In my ionic2 app's packages.json file, I have a dependency on [email protected]. Additionally, I have the latest version of ionic-native which is dependent on [email protected]. Th ...

Tips for implementing an asynchronous function that needs to finish before proceeding in a React class component

I am facing a challenge in creating an async function within a React class component that needs to be completed before rendering. I prefer not to use lifecycle methods like componentDidMount, so I decided to utilize top-level await in the following manner: ...

Is there a way I can conduct a search that includes both uppercase and lowercase characters simultaneously?

My current task is to create a search function that can search for elements in both lower and upper case, regardless of the case typed in by the user. I have attempted to implement a search feature that covers both upper and lower case scenarios, but it s ...

How to Extract the Specific Parameter Type from a Function in Typescript

After generating a client for an API using typescript-node, I encountered the following code: export declare class Api { getUser(username: string, email: string, idType: '1298' | '2309' | '7801') } I need to access the ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

A guide to limiting the input range in React Native's TextInput field

Is there a way to limit user input to a minimum value of 0 and a maximum value of 100? I've tried validating the data during the onTextChanged event, but it's causing the UI to re-render, which is not the desired effect. I want the same behavior ...

Tips for managing local storage asynchronously

I have two files in my TypeScript application, namely: File 1 and File 2, In File 1, I want to save a value in local storage like this: private load() { return this.entityService .load(this.$scope.projectRevisionUid) ...

Implementing click event binding with various CSS styles in Angular

Is there a way to attach multiple css classes to the click event of the Submit button in Angular? I want the style to change when the button is clicked. HTML <div class="mainbody" [ngClass]="getStyle"> <button (click)=&quo ...

Data filtering in the bigtable system

My table consists of a rowKey and 2 columns. The RowKey is in the format string#timestamp, with the first column containing a String value and the second column containing JSON as a String. Query query = Query.create(bigTableTableName).range(rowKey ...