vue-mc
vue-mc copied to clipboard
Support to non-HTTP RESTful models: Firebase and Firestore
Hi there,
I use firebase for my app and firestore as backend/DB so I developed a FirestoreModel that inherits from vue-mc Model, but i'm missing something, how would you implement such model? The general question is, how would you implement a model that doesn't have an HTTP RESTful API but something custom?
Here an example for fetch:
FirestoreModel.js
import { Model } from 'vue-mc'
import { fetch, save, _delete } from './FirestoreCommon'
export default class FirestoreModel extends Model {
fetch (params) {
const url = this.getURL(this.getFetchRoute(), params)
this.onFetch()
let ref = firestore.collection(url)
if (params.where) {
for (let w of params.where) {
ref = ref.where(...w)
}
}
ref.get()
.then(this.onFetchSuccess)
.catch(this.onFetchFailure)
}
onFetchSuccess (snapshot) {
let attributes = null
if (snapshot.exists) {
attributes = snapshot.data()
attributes.id = snapshot.id
} else {
throw String('No data in fetch response')
}
}
}
models/Expense.js
export default class Expense extends FirestoreModel {
}
This is working but it does support only basic features, now i'm implementing the search (see .where()).
I also have an issue, when you fetch() a firestore date field, it is a custom object, but when you save() it, it has to be a Date object: how can I handle such asymmetric transformation?
Anyone else with the same issue? Any idea?
Luca
I'm trying to connect my vue-mc models to Firestore for fetch and save as well, are there any examples for this?
@dalezak I created a gist with the code I'm currently using:
FirestoreModel.jsandFirestoreCollection.jsare VueMC Firestore equivalent for Model and Collection, your models have to inherit from theseActivity.jsandActivities.jsare two example models that inherit from the above
This is not a full implementation of VueMC for Firestore, yet it's fine for most common usage, I mostly query firestore collections with where, orderBy and limit and save/delete documents:
this.activities = new Activities()
await this.activities.fetch({
where: [ [ 'project', '==', this.projectId ] ]
})
this.activities.models[2].delete()
Please note: date fields are automatically converted into JS Date objects when fetched from firestore
here the gist: https://gist.github.com/lucafaggianelli/91b1ffa66aac733399888c4bdabf2410
Luca
This is great @lucafaggianelli, thank you! 🙏