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

Waiting for an async reporter callback #218

Closed
Ansis100 opened this issue Mar 1, 2024 · 3 comments
Closed

Waiting for an async reporter callback #218

Ansis100 opened this issue Mar 1, 2024 · 3 comments

Comments

@Ansis100
Copy link

Ansis100 commented Mar 1, 2024

I'd like to log envalid errors to our log aggregation service. However, the logger function is async, which means that the reporter callback also has to be async. Here's a pseudocode-y example:

const goodEnv = cleanEnv(env, validators, {
  reporter: async ({ errors }) => {
    await logger(errors);
    process.exit(1);
  }
});

The issue is that the goodEnv should not be used until it is fully checked, which is why there is a process.exit in the reporter - to stop further code from using an unchecked environment. However, the application will only exit when the logger function has finished, which means that further code has a chance to mess something up while it is logging. I also can't make the logger function synchronous because then the logging service request will be cancelled by the application exiting.

Is there any way to make cleanEnv return a promise that resolves when everything is finished, including reporter calls?

@Ansis100
Copy link
Author

Ansis100 commented Mar 1, 2024

Side note - I'm pretty sure this would mean changes in the cleanEnv code for my specific case. If that's not possible then maybe I can just call the validator functions myself, basically reimplementing cleanEnv?

@SimenB
Copy link
Collaborator

SimenB commented Mar 1, 2024

problem with this is that I think that means cleanEnv needs to be async as well, which is very breaking.

What about:

let reporterErrors;

const goodEnv = cleanEnv(env, validators, {
  reporter: ({ errors }) => {
    reporterErrors = errors;
  }
});

if (reporterErrors) {
  await logger(errors);
  process.exit(1);
}

?

@Ansis100
Copy link
Author

Ansis100 commented Mar 12, 2024

This is exactly what I needed. I'm not sure why I didn't think of that. My bad. Thank you for the suggestion!

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

2 participants