mission-completed
v0.1.10
Published
Stop processing even if Cloud Functions fires multiple times.
Downloads
6
Maintainers
Readme
mission-completed
Note: Trigger events are delivered at least once, which means that rarely, spurious duplicates may occur. https://cloud.google.com/functions/docs/concepts/events-triggers#triggers
Cloud Functions rarely fire multiple times. If multiple payment occurs, it is a big problem!!
mission-completed uses transactions to prevent multiple trigger events.
If you try to set the completed flag to true many times, CompletedError will be returned.
await Mission.markCompleted(ref, id) // first: success
await Mission.markCompleted(ref, id) // second: throw CompletedError
Results are saved like this.
Install
yarn install mission-completed
Usage
This sample is written in TypeScript.
1. Initialize
Initialize event-response in your index.ts.
import * as Mission from 'mission-completed'
import * as functions from 'firebase-functions'
Mission.initialize(functions.config().firebase)
2. mark completed in Cloud Functions
If mission has already been completed, throw CompletedError in Mission.markCompleted(event.data.ref, 'updateUser')
.
exports.updateUser = functions.firestore.document('users/{userId}')
.onCreate(async event => {
try {
await Mission.markCompleted(event.data.ref, 'updateUser')
} catch (error) {
if (error.constructor === Mission.CompletedError) {
console.error(error, 'Mission has already been completed.')
return Promise.reject(error)
}
}
await event.data.ref.update({updated: true})
return undefined
})
This will continue the initial process, but the simultaneous firing process will stop with CompletedError.
License
MIT