Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create "ensure" method #2715

Open
ORESoftware opened this issue Mar 13, 2024 · 0 comments
Open

Create "ensure" method #2715

ORESoftware opened this issue Mar 13, 2024 · 0 comments

Comments

@ORESoftware
Copy link

ORESoftware commented Mar 13, 2024

Motivation

Allow node.js routines to reconnect if not connected

Basic Code Example

this is a good pattern!
the code before:

const client = redis.createClient({
  url: 'redis://localhost:6379'
});

client.connect().catch(err => {
  log.error('redis could not connect:', err);
});

async function performOp(key: string, value: string): Promise<bar> {
  try {

    const result = await client.set(key, value, {
      NX: true, // Only set the key if it does not already exist
    });

the code after:

const client = redis.createClient({
  url: 'redis://localhost:6379'
});

client.connect().catch(err => {
  log.error('redis could not connect:', err);
});

(client as any).ensure = async () => {   // <<< this one
  if (client.isOpen) {
    return;
  }
  return client.connect();
}


async function performOp(key: string, value: string): Promise<bar> {
  try {

    await (client as any).ensure();  // <<< THIS ONE

    const result = await client.set(key, value, {
      NX: true, // Only set the key if it does not already exist
    });

this is a really good pattern that has served me well in multiple languages/runtimes over the years. Sure we might still get an error, but it will be a simple subset of the existing way.

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant