Set timeout for Firebase HTTPS Cloud Function - javascript

As per the documentation you can specify the timeout for a function like so:
const runtimeOpts = {
timeoutSeconds: 300,
memory: '1GB'
}
exports.myStorageFunction = functions
.runWith(runtimeOpts)
.storage
.object()
.onFinalize((object) = > {
// do some complicated things that take a lot of memory and time
});
However, the following code fails to deploy, with error TypeError: functions.https.runWith is not a function:
const admin = require("firebase-admin");
const functions = require("firebase-functions");
admin.initializeApp();
exports.hello = functions.runWith({ timeoutSeconds: 540 }).https.onRequest(async (req, res) => {
res.send("hello");
});
What is wrong?

Related

Does express-rate-limit work on server requests from client side?

So I have a web app I've built with react and javascript that consists of a server side and a client side.
This is what I set up on the server app.js:
require("./DB/connectToDb");
// require("./primeryData/primeryCards")();
const express = require("express");
const app = express();
const rateLimit = require("express-rate-limit");
const usersRouter = require("./Routes/Users/userRouter");
const cardsRouter = require("./Routes/Cards/cardsRouter");
const ordersRouter = require("./Routes/Orders/OrderRouter");
const chalk = require("chalk");
const morgan = require("morgan");
const cors = require("cors");
app.use(morgan(chalk.cyan(":method :url :status :response-time ms")));
app.use(cors());
app.use(express.json());
app.use("/api/users", usersRouter);
app.use("/api/cards", cardsRouter);
app.use("/api/orders", ordersRouter);
const PORT = 8181;
app.listen(PORT, () =>
console.log(chalk.blueBright.bold(`server run on: http://:localhost:${PORT}`))
);
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
message: "Limited I Guess..."
})
app.get("/",limiter,(req,res)=>res.send(req.ip));
app.use('/api', limiter);
When I go to the Browser with http://localhost:8181/ I get my IP which is ::1
After refreshing >10 times I get "Limited I Guess..." as it should.
However when I try and use my client side to make requests nothing happens, I can make a million server calls!!!
Am I missing something? Does express-rate-limit not work when client side is making the server calls?
An example of my server api:
/********** Like/Dislike Card **********/
router.patch("/card-like/:id", auth, async (req, res) => {
try {
// console.log(req.params.id);
const user = req.user;
let card = await Card.findOne({ _id: req.params.id });
const cardLikes = card.likes.find((id) => id === user._id);
if (!cardLikes) {
card.likes.push(user._id);
card = await card.save();
return res.send(card);
}
const cardFiltered = card.likes.filter((id) => id !== user._id);
card.likes = cardFiltered;
card = await card.save();
return res.send(card);
} catch (error) {
console.log(chalk.redBright("Could not edit like:", error.message));
return res.status(500).send(error.message);
}
});
I was using the library in app.js, tried using it in api.js and worked I guess, app.js was unaware of what was going on in api.js even though it was required.

access-Control-Allow-Origin when Call functions from your app

I am trying to call firebase function from my web app
I am getting
access-Control-Allow-Origin error
My code is from web:
var createNewUserAndEvent = firebase.functions().httpsCallable('createNewUserAndEvent');
const data= await createNewUserAndEvent(userData);
and from firebase function:
const functions = require("firebase-functions");
var admin = require("firebase-admin");
admin.initializeApp();
exports.createNewUserAndEvent = functions.https.onCall((data, context) => {
cors({ origin: true })(data, context, async () => {
if (!context.auth) {

Error with firebase deploy only functions

I have issue with firebase i try to deploy a new functions but i got this error:
Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logsFunctions deploy had errors with the following functions:api
my index.js in the functions folder is:
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")("--TOKEN_HERE--");
// API
// - App config
const app = express();
// - Middlewares
app.use(cors({ origin: true }));
app.use(express.json());
// - API routes
app.get("/", (request, response) => response.status(200).send("hello world"));
app.post("/payments/create", async (request, response) => {
const total = request.query.total;
console.log("Payment Request Recieved BOOM!!! for this amount >>> ", total);
const paymentIntent = await stripe.paymentIntents.create({
amount: total, // subunits of the currency
currency: "usd",
});
// OK - Created
response.status(201).send({
clientSecret: paymentIntent.client_secret,
});
});
// - Listen command
exports.api = functions.https.onRequest(app)
Anyone have an idea?

Firebase cloud functions not updating when deployed - still serving old version of function

I'm frustrated and confused. I'm trying to deploy my cloud functions but whenever I do they're not updating properly and despite firebase saying that they were updated successfully, keep serving the old function. Here's my index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
//Cloud functions for user interaction
const charge = require('./func/charge');
const addProduct = require('./func/addProduct');
const removeProduct = require('./func/removeProduct');
const updateTracking = require('./func/updateTracking');
admin.initializeApp(functions.config().firebase);
exports.charge = functions.https.onRequest(charge);
exports.updateTracking = functions.https.onRequest(addProduct);
exports.addProduct = functions.https.onRequest(removeProduct);
exports.removeProduct = functions.https.onRequest(updateTracking)
And here's my addProduct function with everything stripped away. This still doesn't update.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const request = require('request');
const send = require('../send.js');
const cors = require('cors')({origin: '*'});
function addProduct(req, res) {
console.log('THIS NEVER PRINTS')
send(res, 500, {
error: `FAILURE`
})
}
const appAddProduct = express();
appAddProduct.use(cors);
appAddProduct.post('/', (req, res) => {
// Catch any unexpected errors to prevent crashing
try {
addProduct(req, res);
} catch(e) {
console.log(e);
send(res, 500, {
error: `The server received an unexpected error. Please try again and contact the site admin if the error persists.`,
});
}
});
module.exports = appAddProduct
This is still serving up a success message & status code 200 from an older function with a logic error in it when this should just be serving up a 500 error every time. Something is clearly wrong with the way I've split this into multiple files as that is where the trouble started but I'm not sure where I've gone wrong. Help would be much appreciated.
Your exported function names don't match the names of the imported files:
exports.charge = functions.https.onRequest(charge);
exports.updateTracking = functions.https.onRequest(addProduct);
exports.addProduct = functions.https.onRequest(removeProduct);
exports.removeProduct = functions.https.onRequest(updateTracking)
I see that three of the four functions are not paired with the same-named imports. The only one that matches is charge. I suspect you didn't intend to do this.

Deploy or Run Functions Locally (HTTP functions + Realtime Database functions )

How can I run HTTP functions and Realtime Database functions simultaneously
I see in the documentation here : Run functions locally how to run HTTP functions by the following command : firebase serve and for the Realtime Database functions : firebase functions:shell but it doesn't work for me.
And also when I deployed my functions with command firebase deploy --only functions it only deploy my HTTP function .
What is wrong with my approach ?
structure:
/functions
|--index.js
|--saveDetectedBeacons.js
|--generatePresence.js
|--package.json
index.js:
const functions = require('firebase-functions');
const admin = require("firebase-admin");
const saveDetectedBeaconsFunc = require('./saveDetectedBeacons');
const generatePresenceFunc = require('./generatePresence');
const serviceAccount = require("./serviceAccountKey");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://exampleDb.firebase.com"
});
const db = admin.database();
exports.saveDetectedBeaconsApi = functions.https.onRequest((request, response) => {
saveDetectedBeaconsFunc.handler(request,response,db)
});
exports.generatePresenceApi = functions.database.ref('/reports').onCreate((snapshot, context) => {
generatePresenceFunc.handler(snapshot, context, db)
});
saveDetectedBeacons.js:
exports.handler = function (request, response, db) {
// do something
};
generatePresence.js
exports.handler = function (snapshot, context, db) {
// do something
};

Categories