-
Notifications
You must be signed in to change notification settings - Fork 13
User's Guide 03:01 Dependency Injection
If you're using Typescript, you've probably already been warned that this is
coming, but, yeah--TaskBotJS supports (one could say "mandates") that you as a
developer consider the dependencies for your job. It is totally possible to just
use global variables or singletons import
ed out of other files, but I hope
that you won't. And I hope that for a couple reasons:
- It is way harder to build a job which you can test by injecting/mocking dependencies like database connections, API clients, and the like.
- It's more difficult to understand what the external dependencies of a given piece of code are in the case of refactors and the general process of understanding what any given part
Using this is easy. If you're using JavaScript, you just pass a function to your
Config
object. That function takes as arguments a Bunyan logger and a TaskBotJS
client (conventionally called taskbot
), then returns an object that can be any
object that contains at least those fields. The default implementation of your
dependencies provider is pretty easy:
(baseLogger, taskbot) => ({ baseLogger, taskbot })
It's not that much more complicated to use in TypeScript--implement or extend
the IDependencies
interface and pass in a function that conforms to
DependencyFactory<TDependencies>
and you're done.
TypeScript heads will probably notice that this isn't a cure-all solution to
all your woes. You have some wink-wink flexibility when using JavaScript, but
all jobs implemented in TypeScript have to implement Job<TDependencies>
with
the same generic argument. Which is kind of a bummer, as it would be nice to be
able to declare them with different sets of dependencies and be both typesafe
and clever about it. On the future roadmap for a later major release of TaskBotJS
is to do exactly that. However, in the interim, hey--we've at least made our
code explicit and more easily testable. Baby steps!