Search code examples
typeorm

How can I manage entities implementing a common interface?


I know that I can implement an interface when defining an Entity, but I want to be able to treat all implementations of this interface as if they had a shared table, with a common Repository. To better illustrate my problem, here a two examples:

GitHub repository owners

On GitHub both users and organizations can own repositories. Let's imagine there is a User and an Organization entity. They both implement the RepositoryOwner interface that specifies stuff like an array of Repository's as a relation.

Now take a look at GitHub's "Trending developers" page. It treats User's and Organization's equally as if there was a common Repository<RepositoryOwner> that could be used to fetch the data.

Resource sharing site

A site where users can upload different types of resources like images, videos and documents. All of these types have their own Entity with different properties, but all of them implement the Resource interface. On a user's profile page there's a list of all the resources uploaded by this user. A Repository<Resource> would be very helpful again, the type of a resource is determined using typeof and displayed using an icon.


Solution

  • I'm assuming that you intend to share a common table from which you want to derive two more tables? In that case you can define an interface IRepositoryOwner and implement it in a base entity RepositoryOwner. And then extend RepositoryOwner to Organization and User entities.

    This would allow you to retrieve an array of RepositoryOwners but repositoryOwner instanceof User would be false. And casting repositoryOwner to User would not be possible. You'd be missing the derived class properties.