Firestore: data model definition and validation

51 views
Skip to first unread message

Luca Faggianelli

unread,
Jul 28, 2019, 7:47:45 AM7/28/19
to Firebase Google Group
I'm using Firestore for a quite large app and dealing with all models became a problem, I needed a decent way to declare models, validate and save them.

I share what I did and I'm curious to understand what approach you used. My app is based on Vue and I've found vuemc, out of the box it doesn't support firestore, though I created a plugin to add support so now I'm able to define models like this:

```javascript
export default class Activity extends FirestoreModel {
  modelName = 'Activity'
  collection = 'activities'
  autoFields = true

  defaults () {
    return {
      id: null,
      parentId: null,
      title: '',
      owner: '',
      startDate: moment().toDate(),
      dueDate: moment().add(1, 'week').toDate(),
      effort: 0,
      progress: 0,
      order: 0,
      successors: {}
    }
  }

  validation () {
    return {
      startDate: date,
      dueDate: date,
      effort: gte(0),
      progress: between(0, 100),
      order: gte(0)
    }
  }
}
```

and then:
```
const project = new Project()
project.fetch({ where: [[ 'createdBy', '==', 'me' ]] })

project.name = 'Awesome project'
// When saving, updates fields like createdAt, updatedAt, createdBy and shows notifications
project.save()
```

When you edit a model in a form, VueMC keeps separated the saved attributes and the modified ones, so you don't need to copy objects before editing, it also has validation rules that prevents you from saving bad data and I'm using those rules also for graphical form validation.

Another topic is Vuex or analogous store in other frameworks, I use a library (vuexfire) to keep in sync firestore data with store data, without using the

An annoying thing is that I have to duplicate models definition for both the client and firestore rules.

So how are you dealing with data in firestore?
Luca
Reply all
Reply to author
Forward
0 new messages