Model instance methods (save, delete, etc?) #1781
Unanswered
JeffJassky
asked this question in
Q&A
Replies: 1 comment 1 reply
-
I've implemented a version of this using the following approach (warning: pseudocode) PageRepo.ts: import { useRepo } from 'pinia-orm'
import PageModel from './Page.model'
export class PagesRepository extends Repository<PageModel> {
use = PagesModel
...
}
export const usePagesRepo = () => useRepo(PagesRepository) PageModel.ts: import { usePageRepo } from './PageRepo.ts'
export default class PageModel extends BaseDocumentModel {
static entity = 'Page';
public save(){
usePageRepo().save(this)
}
public destroy(){
usePageRepo().destroy(this)
}
} I'm curious - is there anything particularly wrong with this approach? Circular references, memory use, etc... I'm still in the early stages of developing a new product and so haven't tested this at scale yet. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've been exploring ways to streamline interactions with model instances, particularly in the context of common operations like deleting or saving records.
Currently, we use a pattern like
userRepo.destroy(user.id)
oruserRepo.save(user)
. However, adopting a more intuitive approach, like asuser.destroy()
oruser.save()
, could significantly improve developer experience by making the code more readable and easier to write.Example problem:
Often, model instances are provided to a component via prop or some other reference. If that component needs to mutate the instance, the current method requires us to load an instance of the repository. Having direct access to save and destroy on the instance itself would greatly reduce boilerplate code of.
Current approach:
Note: the "user" is an instance of a UserModel, provided via prop, or other reference.
Proposed Improvement:
It seems the code could be minimal such as:
While digging into the source code, I noticed that model instances don't have a direct reference to their repository, which is a barrier to implementing such instance methods directly. The
model.$storeName()
method could theoretically provide access to the underlying Pinia store, but direct manipulation of the Pinia state bypasses model hooks, leading to less maintainable code.I'm interested in hearing the community's thoughts on this. Are there existing discussions or solutions I might have missed? How might we approach this enhancement while ensuring backward compatibility and maintaining the integrity of model hooks? Below are examples of the current and suggested approaches for comparison:
I believe this change could make our interactions with models more intuitive and fluent. I'm open to feedback, suggestions, and further discussions on this topic.
Thank you for considering my proposal.
Beta Was this translation helpful? Give feedback.
All reactions