I have two TypeScript classes, AuditableStore and SearchableStore, both extending a base class Store. I want to create a new class called MyStore that combines the functionalities of both AuditableStore and SearchableStore.
Here are the definitions of the existing classes:
// Store.ts
export class Store<T extends { key: string }> {
protected readonly storeOptions?: StoreOptions<T>;
private readonly storeName: string;
constructor(storeName: string, options?: StoreOptions<T>) {
this.storeName = storeName;
this.storeOptions = options;
}
save(data: T) {
console.log('Save Implementation');
}
protected beforeSave(entity: T): T {
console.log('Default Before Save');
return entity;
}
// ...other store functions
}
// AuditableStore.ts
import { Store } from './Store';
export class AuditableStore<T extends { key: string }> extends Store<T> {
protected readonly auditUser: string;
constructor(
storeName: string,
options: StoreOptions<T> = {},
auditUser: string,
) {
super(storeName, options);
this.auditUser = auditUser;
}
protected beforeSave(data: T): T {
console.log('Execute some audit logic');
return data;
}
}
// SearchableStore.ts
import { Store } from './Store';
export class SearchableStore<T extends { key: string }> extends Store<T> {
constructor(
storeName: string,
options: StoreOptions<T> = {},
) {
super(storeName, options);
}
save(data: T) {
super.save(data);
console.log('Implement searchable logic here');
}
}
What I Want to Achieve:
I want to create a new class called MyStore that combines both AuditableStore and SearchableStore. The goal is for MyStore to:
- Use the AuditableStore logic when I call
myStore.beforePersist(data)
- Use the SearchableStore logic when I call
myStore.save(data)
- Ensure MyStore has access to all other store functions (e.g. delete, read, update)
Questions:
- Is Composition the best approach here?
- If so, how can I compose AuditableStore and SearchableStore into a new class MyStore while maintaining both functionalities?
- What is the best approach to ensure that MyStore correctly implements and utilizes both the audit and searchable features?
Any guidance or examples on how to achieve this composition in TypeScript would be greatly appreciated! I always get a little lost when it comes to Composition in Typescript.
1