When I run firebase deploy --only functions I get this error message:
Error parsing triggers: Cannot find module './clone.js'
Here's my code, copied from the documentation:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {Storage} = require('#google-cloud/storage');
const storage = new Storage();
const bucketName = 'myapp.appspot.com';
const filename = './hola_mundo.wav';
admin.initializeApp();
exports.Storage = functions.firestore.document('Test_Value').onUpdate((change, context) => {
storage.bucket(bucketName).upload(filename, {
gzip: true,
metadata: {
cacheControl: 'no-cache'
}
})
.then(() => {
console.log(`${filename} uploaded to ${bucketname}`);
})
.catch(err => {
console.error(err);
});
});
Is clone.js this npm module?
I moved the constants into the function and the error went away:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.Storage = functions.firestore.document('Test_Value').onUpdate((change, context) => {
const {Storage} = require('#google-cloud/storage');
const storage = new Storage();
const bucketName = 'myapp.appspot.com';
const filename = './hola_mundo.wav';
storage.bucket(bucketName).upload(filename, {
gzip: true,
metadata: {
cacheControl: 'no-cache'
}
})
.then(() => {
console.log(`${filename} uploaded to ${bucketname}`);
})
.catch(err => {
console.error(err);
});
});
Related
I am uploading the image to firebase storage, it is uploaded successfully but I don't know how to get the image url in the firebase.`
const mongoose = require("mongoose");
const express = require("express");
const cors = require("cors");
const cookieparser = require("cookie-parser");
const Multer = require("multer");
const FirebaseStorage = require("multer-firebase-storage");
const dotenv = require("dotenv");
const path = require("path");
//logger
const logger = require("./utils/logger");
//routes
const verifyToken = require("./middleware/authJWT");
const { UserType } = require("./constants/user-types");
const app = express();
dotenv.config();
app.use(cors());
app.use(express.json());
app.use(cookieparser());
app.use("/images", express.static(path.join(__dirname, "/images")));
mongoose
.connect(process.env.MONOGO_URL)
.then(console.log("Connected to MongoDB"))
.catch((err) => console.log(err));
const multer = Multer({
storage: FirebaseStorage({
bucketName: process.env.FIREBASE_BUCKET_NAME,
credentials: {
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY,
projectId: process.env.FIREBASE_PROJECT_ID,
},
}),
});
app.post(
"/api/upload",
[verifyToken(UserType.ADMIN), multer.single("file")],
(req, res) => {
logger.info("uploading imagee.....");
res.status(200).send(req.file);
}
);
app.listen("5001", () => {
console.log("Backend is running.");
});
`
I have uploaded the image using multer, I want image url from the firebase as a response to the endpoint.
is there any way to deploy OpenTelemetry in next.js without having to create a custom server?
what I found would boil down to the following codes:
tracing.js:
'use strict'
const opentelemetry = require('#opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('#opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('#opentelemetry/exporter-otlp-grpc');
const { Resource } = require('#opentelemetry/resources');
const { SemanticResourceAttributes } = require('#opentelemetry/semantic-conventions');
// custom nextjs server
const { startServer } = require('./server');
// configure the SDK to export telemetry data to the console
// enable all auto-instrumentations from the meta package
const exporterOptions = {
url: 'http://localhost:4317',
}
const traceExporter = new OTLPTraceExporter(exporterOptions);
const sdk = new opentelemetry.NodeSDK({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'SigNoz-Nextjs-Example'
}),
traceExporter,
instrumentations: [getNodeAutoInstrumentations()]
});
// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk.start()
.then(() => console.log('Tracing initialized'))
.then(() => startServer())
.catch((error) => console.log('Error initializing tracing', error));
// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));
});
module.exports = sdk
server.js:
const { createServer } = require("http")
const { parse } = require("url")
const next = require("next")
const dev = process.env.NODE_ENV !== "production"
const app = next({ dev })
const handle = app.getRequestHandler()
module.exports = {
startServer: async function startServer() {
return app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
}).listen(8080, (err) => {
if (err) throw err
console.log("> Ready on http://localhost:8080")
})
})
},
}
this comes from this link.
I don't think it's a right and "clean" approach. How do I implant in a less "invasive" way?
I am building cloud functions for the backend of my app but I couldn't figure out a way to use the app or db variables without passing them into my functions as parameters. I tried initializing the apps seperately in its own functions but multiple app initialization of the same app is not allowed but I want to use only one app.
So the question is, is there a way to implement the below code without passing the app/db parameter into every function?
PS: Also I would appreciate if you could suggest few tips to improve the quality of the file structuring and how I import / export functions.
index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const cors = require("cors")({ credentials: true, origin: true });
const app = admin.initializeApp();
const db = app.firestore();
const { addVehicle } = require("./src/vehicles/addVehicle");
const { getVehicles } = require("./src/vehicles/getVehicles");
exports.addVehicle = functions.https.onRequest(async (req, res) => {
cors(req, res, async () => {
const result = await addVehicle(req, res, db);
res.json((result));
});
});
exports.getVehicles = functions.https.onRequest(async (req, res) => {
cors(req, res, async () => {
res.json((await getVehicles(req,res,db)));
});
});
addVehicle.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const Vehicle = require("../../models/Vehicle");
exports.addVehicle = async (req, res, db) => {
try{
const vehicleInfo = new Vehicle(req.body);
const addedVehicle = await db.collection("vehicles").add(vehicleInfo);
console.log(addedVehicle);
res.json({data: "Succesfully added vehicle"});
}
catch(err){
if(err){
res.json(err);
}
}
};
getVehicles.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const Vehicle = require("../../models/Vehicle");
exports.getVehicles = async (req, res, db) => {
try{
const vehiclesSnapshot = await db.collection("vehicles").get();
const vehicles = [];
vehiclesSnapshot.forEach(doc => {
vehicles.push(doc.data());
});
res.json({ data: vehicles });
}
catch(err){
if(err){
res.json(err);
}
}
};
I'm trying to write a simple function which takes a request containing multipart/form data and uploads the image to the firebase cloud storage using busboy, but in the cloud functions console it throw the following error "TypeError: Cannot read property 'file' of null". I have checked if the postman sends the correct header 'Content-type: multipart/form-data' and everything seems to be ok. Any help will be much appreciated.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const os = require('os');
const path = require('path');
const fs = require('fs');
const Busboy = require('busboy');
var { Storage } = require('#google-cloud/storage');
var gcs = new Storage({
projectId: 'xxxxxxxxxxxxxxx',
keyFilename: 'xxxxxxxxk-y7fqf-38xxx5121.json'
});
exports.uploadFile = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if (req.method !== "POST") {
res.status(500).json({
message: "Not allowed"
});
}
console.log(req.body)
const busboy = new Busboy({ headers: req.headers });
let uploadData = null;
busboy.on('file', function (fieldname, file, filename, encoding,
mimetype) {
const filepath = path.join(os.tmpdir(), filename);
uploadData = { file: filepath, type: mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
const bucket = gcs.bucket("xxxxxxxxxxx.appspot.com");
// const bucket = admin.storage().bucket();
bucket
.upload(uploadData.file, {
uploadType: "media",
metadata: {
metadata: {
contentType: uploadData.type
}
}
})
.then(() => {
res.status(200).json({
message: "It worked!"
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
req.pipe(busboy)
});
});`
I'm changing real time database to Firestore.
Using cloud function trigger onUpdate() always failed with error message.
here's my cloud function index.js
const admin = require("firebase-admin");
const functions = require("firebase-functions");
const serviceAccount = require("./service_account.json");
const friendProcess = require("./friend_process");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://projec-name.firebaseio.com"
});
exports.friendProcess = functions.firestore.document("users/{userId}/friends/{requestId}").onUpdate(friendProcess);
and this code is friend_process.js
const admin = require("firebase-admin");
module.exports = function(event) {
const userId = event.params.userId;
const updatedData = event.data.data();
const requestId = updatedData.fromUid;
const previousData = event.data.previous.data();
console.log("update data", updatedData);
console.log("requestId", requestId);
console.log("userId", userId);
if (previousData.status === "request" && updatedData.status === false) {
console.log("updatedData.action ", updatedData);
console.log("ref", event.data.ref);
return admin
.firestore()
.collection("users")
.doc(requestId)
.collection("friends")
.doc(userId)
.get()
.then(doc => {
return console.log("doc ", doc);
})
.catch(error => {
return console.log("error ", error);
});
}
return;
};
here's my console log
firebase console log link
Error: Unexpected error while acquiring application default credentials: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.
at GoogleAuth. (/user_code/node_modules/firebase-admin/node_modules/google-auth-library/build/src/auth/googleauth.js:229:31)
at step (/user_code/node_modules/firebase-admin/node_modules/google-auth-library/build/src/auth/googleauth.js:47:23)
at Object.next (/user_code/node_modules/firebase-admin/node_modules/google-auth-library/build/src/auth/googleauth.js:28:53)
at fulfilled (/user_code/node_modules/firebase-admin/node_modules/google-auth-library/build/src/auth/googleauth.js:19:58)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
my package.json
"firebase-admin": "^5.11.0",
"firebase-functions": "^0.9.1",