Skip to content

Stop processing even if Cloud Functions fires multiple times.

License

Notifications You must be signed in to change notification settings

starhoshi/mission-completed

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mission-completed

npm version Build Status Codacy Badge License: MIT

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