Suggestion: BaseModel configuration prop
See original GitHub issueProposal
Add a BaseModel to host static methods for models
How it could work
- Add optional config
BaseModel - If
BaseModelis declared, as soon as the database has ahandle, it wouldBaseModel.database = database, even before declaringcollectionMap
Example
I have 32 model classes atm, and for collection methods I decided to use Model’s static methods. For example:
Post.find() is basically: database.collections.get('posts').find() but In a way nicer way.
Instead of just adding it to each class, I created a class BaseModel extends Model and all my classes extend this BaseModel.
So I added in Base Model methods like:
static getCollection<T extends typeof Model>(
this: T,
): Collection<InstanceType<T>> {
const database = ((this as unknown) as BaseModel).database;
return database.get<InstanceType<T>>(this.table);
}
static async find<T extends typeof BaseModel>(this: T, id: string) {
let item: InstanceType<T> | undefined;
try {
item = await this.getCollection().find(id);
} catch (e) {
this.registerNotFound(id);
}
return item;
}
static async findBy<T extends typeof BaseModel>(
this: T,
fieldName: string,
value: string,
) {
let item: InstanceType<T> | undefined;
let itemArray = await this.fetchBy(fieldName, value, Q.experimentalTake(1));
try {
item = itemArray[0];
} catch (e) {
this.registerNotFoundBy(fieldName, value);
}
return item;
}
static findAndObserve<T extends typeof BaseModel>(this: T, id: string) {
return this.getCollection().findAndObserve(id);
}
This allows me to write cleaner code, for example in observables:
export const withPostsForHome = withObservables([], () => ({
posts: Posts.postsForHome(),
}));
The only issue is that I set the BaseModel database way after the database is ready, having some errors once in a while, especially when hot reloading a model.
So I’m suggesting this change in the hope I reduce (or zero) the current issues.
If agreed, I would love to write the changes but I will need help with typing
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:9 (7 by maintainers)

Top Related StackOverflow Question
sorry, but it’s a no from me. This was considered and rejected, oh, like 4 years ago.
Posts.foo()is nice, but it’s not clean. I refuse to promote a coding practice that implicitly make aDatabasea singleton. You should be able to have multiple instances of a Database, of a Collection, etc., and this proposal prevents that.What we practice at Nozbe is that there’s a
ModelRootinstance that contains methods that act on the whole database (when there is no Model instance where the method fits) - e.g. yourpostsForHomewould be there. This object is available the same way as a Database:Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.