Skip to content

Instantly share code, notes, and snippets.

@coderbyheart
Last active November 29, 2018 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderbyheart/bf6d16c6bf3d08acd547642a4d7e3e07 to your computer and use it in GitHub Desktop.
Save coderbyheart/bf6d16c6bf3d08acd547642a4d7e3e07 to your computer and use it in GitHub Desktop.
Classes vs Functions (TypeScript and Dependency Injection)
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
}
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