I'm completely stumped on how to avoid this circular dependency. I have a TS module that sends emails, and one that handles errors. The error handler writes to a DB and sends emails. And the emailer needs to be able to handle errors. Then most apps use both of them.
For example, something like:
emailer.js
import err from "error-handler.js"
function sendEmail() {
try { trySendEmail() }
catch(e) { err(e) }
}
error-handler.js
import sendEmail from "emailer.js"
function err(e) {
sendEmail("Error Occurred", e)
}
Is there a right way to handle this situation? Thanks for your help!
a) there's absolutely no reason not to use a circular dependency here - the two modules do depend on each other, and the code you've written works as-is with ES6 modules, no problems at all. It's no different from putting both function declarations in the same file.
b) break the dependency chain and use dependency injection instead. Either have
// emailer.js
function sendEmail(text, handleError) {
try { trySendEmail(text) }
catch(e) { handleError(e) }
}
// error-handler.js
import sendEmail from "emailer.js"
function err(e) {
sendEmail("Error Occurred: "+e.message, err)
}
or
// emailer.js
import err from "error-handler.js"
function sendEmail(text) {
try { trySendEmail(text) }
catch(e) { err(e, sendEmail) }
}
// error-handler.js
function err(e, sendEmail) {
sendEmail("Error Occurred: "+e.message)
}
If you still need to use both in your project, without injecting a dependency in either, you'll need a third module that depends on both and does export a function with the dependency injected.