Search code examples
javarestjerseysolid-principlesclean-architecture

How to go about inserting domain objects in db at start of API


Im building a REST API in java with jersey and jetty. I have a complex domain in which I have a class (Workers). I want to be able to dynamically add workers through a POST. However, the business logic requires me to have a few default workers with fixed values. So at the start of the API, I need to add them to my db (right now its in memory). In terms of clean code whats the best way to go about that?

I thought about initializing my repository with these defaults workers, but I feel like its violating the SRP for the WorkerRepo class, I feel like that should be the job of the application layer as its specific to this application, not to the domain if that makes sense. Where should I move the logic for this initialization? Thanks!


Solution

  • After a bit of thinking, I moved the setup in the application layer, where I actually instanciate all my dependencies (in a class named ApplicationContext).

    I created an interface WorkerContext and created a concrete implementation WorkerContextX where X = NAMEOFTHEAPP. This context class contains all the default values and uses the injected repo to add these default values to the repo. So at the startup of the API, in the ApplicationContext class, I call the WorkerContext method that setup my workerRepo.

    This way, I can easily change the setup strategy in the blink of an eye and it doesnt violate the SRP anymore in the repo. And I now respect the DIP as the repo(which was in the domain) doesnt rely on things that are dictated by the application layer.

    I posted this as I thought it was a decent solution and could help other people, feel free to critique or improve this solution.