Created
September 23, 2020 17:46
-
-
Save mcalavera81/827e39c63a0e2394a14ba9b5b152905b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Generic constructor signature | |
type ClassConstructor<T> = new (...args: any[]) => T; | |
// The contraint we might want to apply to our constructor signature | |
export interface IHelperRepository { | |
getEntity<T extends EntityDTO>(entityQuery: EntityQuery): Promise<Maybe<T>>; | |
getItems<T extends SummaryDTO>(itemsQuery: ItemsQuery): Promise<T[]>; | |
} | |
type HelperRepoConstructor = ClassConstructor<IHelperRepository>; | |
// This is the mixin, a function that takes a class constructor and returns a class constructor | |
function withPostProcessing<C extends HelperRepoConstructor>(Class: C) { | |
return class extends Class implements IHelperRepository { | |
public getEntity<T extends EntityDTO>( | |
entityQuery: EntityQuery | |
): Promise<Maybe<T>> { | |
return super.getEntity<T>(entityQuery); | |
//Post process: filtering, logging, transforming,... | |
} | |
getItems<T extends SummaryDTO>(itemsQuery: ItemsQuery): Promise<T[]> { | |
return super.getItems<T>(itemsQuery); | |
//Post process: filtering, logging, transforming,... | |
} | |
}; | |
} | |
// The class with the mixin applied | |
const MyRepoClassWithMixin = withPostProcessing(class implements IHelperRepository{ | |
getEntity<T extends EntityDTO>(entityQuery: EntityQuery): Promise<Maybe<T>> { | |
throw Error() | |
} | |
getItems<T extends SummaryDTO>(itemsQuery: ItemsQuery): Promise<T[]> { | |
throw Error() | |
} | |
}); | |
// Instance of the class with the mixin applied | |
const repoWithMixin = new MyRepoClassWithMixin(); | |
repoWithMixin.getItems(...); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment