Jblew / firebase-functions-rate-limiter

Js/ts library that allows you to set per-time, per-user or per-anything limits for calling Firebase cloud functions
MIT License
100 stars 15 forks source link

It appears your code is written in Typescript, which must be compiled before emulation #10

Closed fer-ri closed 3 years ago

fer-ri commented 4 years ago

Hi, thanks for the package.

I have issue when running this with an emulator locally. This is my code

const admin = require("firebase-admin");
const functions = require('firebase-functions');
const FirebaseFunctionsRateLimiter = require("firebase-functions-rate-limiter");

const serviceAccount = require("service-account.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://firebase-url-here.firebaseio.com",
});

// const database = admin.database();
const firestore = admin.firestore();

const limiter = FirebaseFunctionsRateLimiter.withFirestoreBackend(
  {
    name: "rate_limiter_collection",
    maxCalls: 2,
    periodSeconds: 15,
  },
  firestore
);

exports.helloWorld = functions.https.onRequest(async (request, response) => {
  await limiter.rejectOnQuotaExceededOrRecordUsage();

  response.send("Hello from Firebase!");
});

When running firebase emulators:start then it gives me errors below:

⚠  TypeError: FirebaseFunctionsRateLimiter.withFirestoreBackend is not a function
    at Object.<anonymous> (/home/bolt/dev/console/firebase/functions/index.js:15:46)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at /usr/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:650:33
    at Generator.next (<anonymous>)
⚠  We were unable to load your functions code. (see above)
   - It appears your code is written in Typescript, which must be compiled before emulation.

I use javascript mode in my firebase setup.

Any idea for this? Thanks

luchris11 commented 3 years ago

Seems like you need to have it as

const limiter = FirebaseFunctionsRateLimiter.FirebaseFunctionsRateLimiter.withFirestoreBackend(

and then it worked!

fer-ri commented 3 years ago

I'll try it. Thanks for pointing out.

Jblew commented 3 years ago

Ah, the example is wrong. You need to use:

const { FirebaseFunctionsRateLimiter } = require("firebase-functions-rate-limiter");