Tart is a thin wrapper for Cloud Functions.
Let's define the model and write Cloud Functions with TypesScript.
You can write like this.
import * as Tart from '@star__hoshi/tart'
Tart.initialize(admin.firestore())
interface User extends Tart.Timestamps {
name: string
}
export const updateUser = functions.firestore.document('user/{userId}')
.onCreate(async event => {
const user = new Tart.Snapshot<User>(event.data)
console.log(user.data.name) // => old name
console.log(user.ref) // => DocumentReference
await user.update({ name: 'new name'})
console.log(user.data.name) // => new name
return undefined
})
npm install @star__hoshi/tart --save
yarn add @star__hoshi/tart
import * as Tart from '@star__hoshi/tart'
import * as admin from 'firebase-admin'
admin.initializeApp(<admin.AppOptions>functions.config().firebase)
// Tart expects timestampsInSnapshots to be 'true'
admin.firestore().settings({ timestampsInSnapshots: true })
// both admin sdk and cloud functions are same interface.
Tart.initialize(admin.firestore())
You have to extend Tart.Timestamps
.
interface User extends Tart.Timestamps {
name: string
}
interface Game extends Tart.Timestamps {
price: string
}
Snapshot has 2 local variables.
- ref
- DocumentReference
- data
- T extends Tart.Timestamps
const user = new Tart.Snapshot<User>(snapshot)
console.log(user.data) // => Same as snapshot.data()
console.log(user.ref) // => Same as snapshot.ref
const data: User = { name: 'test' }
const user = Tart.Snapshot.makeNotSavedSnapshot('user', data)
// Save a document
await user.save()
// Batched writes
const batch = admin.firestore().batch()
user.saveWithBatch(batch)
await batch.commit()
[Reference|Nedted] Collection's description is here.
const user = Tart.Snapshot.makeNotSavedSnapshot<User>('user', { name: 'test' })
const game = Tart.Snapshot.makeNotSavedSnapshot<Game>('game', { price: 1000 })
const batch = admin.firestore().batch()
user.saveWithBatch(batch)
user.saveReferenceCollectionWithBatch(batch, 'games', game.ref)
user.saveNestedCollectionWithBatch(batch, 'nestedgames', game.ref)
game.saveWithBatch(batch)
await batch.commit()
Pass path or ref as argument.
const savedUser = await Tart.fetch<User>('user', 'id')
const savedUser = await Tart.fetch<User>(userDocumentReference)
Reload the data.
const savedUser = await Tart.fetch<User>(userDocumentReference)
await savedUser.refresh()
const savedUser = await Tart.fetch<User>('user', 'id')
// Update a document
await savedUser.update({ name: 'new name' })
// Batched writes
savedUser.saveWithBatch(batch)
savedUser.updateWithBatch(batch, { name: 'new name' })
await savedUser.commit()
const savedUser = await Tart.fetch<User>('user', 'id')
// Delete a document
await savedUser.delete()
// Batched writes
savedUser.deleteWithBatch(batch)
await savedUser.commit()