firebase / firebase/functions-samples

Ignoring trigger because the Cloud Firestore emulator is not running (firebase serve)

Closed
#572 57 comments 7 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
12.2k
Forks
3.8k
Avg merge
1d 23h
Merged PRs (30d)
2

Description

### How to reproduce these conditions

**Sample name or URL where you found the bug**
https://github.com/firebase/functions-samples/tree/master/stripe

**Failing Function code used (including require/import commands at the top)**
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const logging = require('@google-cloud/logging')();
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';

// [START chargecustomer]
// Charge the Stripe customer whenever an amount is written to the Realtime database
exports.createStripeCharge = functions.firestore.document('stripe_customers/{userId}/charges/{id}').onCreate(async (snap, context) => {
const val = snap.data();
try {
// Look up the Stripe customer id written in createStripeCustomer
const snapshot = await admin.firestore().collection(`stripe_customers`).doc(context.params.userId).get()
const snapval = snapshot.data();
const customer = snapval.customer_id
// Create a charge using the pushId as the idempotency key
// protecting against double charges
const amount = val.amount;
const idempotencyKey = context.params.id;
const charge = {amount, currency, customer};
if (val.source !== null) {
charge.source = val.source;
}
const response = await stripe.charges.create(charge, {idempotency_key: idempotencyKey});
// If the result is successful, write it back to the database
return snap.ref.set(response, { merge: true });
} catch(error) {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with StackDriver
console.log(error);
await snap.ref.set({error: userFacingMessage(error)}, { merge: true });
return reportError(error, {user: context.params.userId});
}
});
// [END chargecustomer]]

// When a user is created, register them with Stripe
exports.createStripeCustomer = functions.auth.user().onCreate(async (user) => {
const customer = await stripe.customers.create({email: user.email});
return admin.firestore().collection('stripe_customers').doc(user.uid).set({customer_id: customer.id});
});

// Add a payment source (card) for a user by writing a stripe payment source token to Realtime database
exports.addPaymentSource = functions.firestore.document('/stripe_customers/{userId}/tokens/{pushId}').onCreate(async (snap, context) => {
const source = snap.data();
const token = source.token;
if (source === null){
return null;
}

try {
const snapshot = await admin.firestore().collection('stripe_customers').doc(context.params.userId).get();
const customer = snapshot.data().customer_id;
const response = await stripe.customers.createSource(customer, {source: token});
return admin.firestore().collection('stripe_customers').doc(context.params.userId).collection("sources").doc(response.fingerprint).set(response, {merge: true});
} catch (error) {
await snap.ref.set({'error':userFacingMessage(error)},{merge:true});
return reportError(error, {user: context.params.userId});
}
});

// When a user deletes their account, clean up after them
exports.cleanupUser = functions.auth.user().onDelete(async (user) => {
const snapshot = await admin.firestore().collection('stripe_customers').doc(user.uid).get();
const customer = snapshot.data();
await stripe.customers.del(customer.customer_id);
return admin.firestore().collection('stripe_customers').doc(user.uid).delete();
});

// To keep on top of errors, we should raise a verbose error report with Stackdriver rather
// than simply relying on console.error. This will calculate users affected + send you email
// alerts, if you've opted into receiving them.
// [START reporterror]
function reportError(err, context = {}) {
// This is the name of the StackDriver log stream that will receive the log
// entry. This name can be any valid log stream name, but must contain "err"
// in order for the error to be picked up by StackDriver Error Reporting.
const logName = 'errors';
const log = logging.log(logName);

// https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
const metadata = {
resource: {
type: 'cloud_function',
labels: {function_name: process.env.FUNCTION_NAME},
},
};

// https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent
const errorEvent = {
message: err.stack,
serviceContext: {
service: process.env.FUNCTION_NAME,
resourceType: 'cloud_function',
},
context: context,
};

// Write the error log entry
return new Promise((resolve, reject) => {
log.write(log.entry(metadata, errorEvent), (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
}
// [END reporterror]

// Sanitize the error message for the user
function userFacingMessage(error) {
return error.type ? error.message : 'An error occurred, developers have been alerted';
}
**Steps to set up and reproduce**
Windows 10, brand new installation of node 10 and firebase-tools (v 6.9.2).
Follow the instructions on the github page for installing the npm package and setting up stripe key and so on, but instead of firebase deploy, I used firebase serve.
Change node version to 10 in package.json.
Attached stripe example to firebase hosting as well.

**Sample data pasted or attached as JSON (not an image)**

**Security rules used**

### Debug output

**Errors in the [console logs](https://console.firebase.google.com/project/_/functions/logs?search=&severity=DEBUG)**
functions: Using node@10 from host.
+ functions: Emulator started at http://localhost:5001
i functions: Watching "" for Cloud Functions...
i hosting: Serving hosting files from: public
+ hosting: Local server: http://localhost:5000
! Default "firebase-admin" instance created!
! Ignoring trigger "createStripeCharge" because the Cloud Firestore emulator is not running.
! Ignoring trigger "createStripeCustomer" because the Cloud Firestore emulator is not running.
! Ignoring trigger "addPaymentSource" because the Cloud Firestore emulator is not running.
! Ignoring trigger "cleanupUser" because the service "firebaseauth.googleapis.com" is not yet supported.
> (node:23520) DeprecationWarning: grpc.load: Use the @grpc/proto-loader module with grpc.loadPackageDefinition instead

**Screenshots**

### Expected behavior
The local emulator starts running and I can test firebase functions without deploying them.

### Actual behavior
Firebase hosting works fine, but all cloud firestore functions get ignored.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.