Last active
November 29, 2018 07:55
-
-
Save coderbyheart/bf6d16c6bf3d08acd547642a4d7e3e07 to your computer and use it in GitHub Desktop.
Classes vs Functions (TypeScript and Dependency Injection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooManager { | |
private readonly barRepo: BarRepository | |
private readonly userPreferencesRepo: UserPreferencesRepository | |
constructor(barRepo: BarRepository, userPreferencesRepo: UserPreferencesRepository) { | |
this.barRepo = barRepo | |
this.userPreferencesRepo = userPreferencesRepo | |
} | |
async findMyFavoriteBar(user: User): Promise<Bar> { | |
const bars = await this.barRepo.findAll() | |
const { favoriteBar } = await this.userPreferencesRepo.getById(user.id) | |
return bars.find(({name}) => name === favoriteBar) || bars[Math.floor(Math.random() * bars.length)] | |
} | |
} | |
type Bar = { | |
name: string | |
} | |
interface BarRepository { | |
findAll(): Promise<Bar[]> | |
} | |
type UserPreferences = { | |
favoriteBar: string | |
} | |
interface UserPreferencesRepository { | |
getById(id: string): Promise<UserPreferences> | |
} | |
type User = { | |
id: string | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Bar = { | |
name: string | |
} | |
type User = { | |
id: string | |
} | |
type UserPreferences = { | |
favoriteBar: string | |
} | |
const findMyFavoriteBar = async (user: User, findAllBars: () => Promise<Bar[]>, getUserPreferences: (user: User) => Promise<UserPreferences>) => { | |
const bars = await findAllBars() | |
const { favoriteBar } = await getUserPreferences(user) | |
return bars.find(({name}) => name === favoriteBar) || bars[Math.floor(Math.random() * bars.length)] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment