getting error while deploying firebase cloud pub-sub code - javascript

while deploying pub-sub code on firebase i'm getting following error :
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. This is likely due to a bug in the user code. Error message: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /srv/node_modules/#google-cloud/pubsub/build/src/pubsub.js:527
async *listSchemas(view = schema_1.SchemaViews.Basic, options) {
^
I'm not getting why this error is occurring.
following is the code:
exports.publish = async (req, res) => {
if (!req.body.topic || !req.body.message) {
res.status(400).send('Missing parameter(s); include "topic" and "message" properties in your request.');
return;
}
console.log(`Publishing message to topic ${req.body.topic}`);
const topic = pubsub.topic(req.body.topic);
const messageObject = {
data: {
message: req.body.message,
},
};
const messageBuffer = Buffer.from(JSON.stringify(messageObject), "utf8");
try {
await topic.publish(messageBuffer);
res.status(200).send("Message published.");
} catch (err) {
console.error(err);
res.status(500).send(err);
return Promise.reject(err);
}
};

I'm going to guess that this function is set to use the Node 8 runtime, since support for async iterators was added in Node 10. The Pub/Sub library has only supported Node 10 and above since 2.0, so bumping the runtime version on the Firebase function should help:
https://firebase.google.com/docs/functions/manage-functions#set_nodejs_version
Unfortunately I don't have enough points to ask for more details on the original question, but hopefully that helps!

Related

getStaticPaths array.map isn't a function when deploying to Vercel [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed last year.
Code is below, the dev server works perfectly fine without error, however when I try to deploy the site I get this error.
> Build error occurred
TypeError: artists.map is not a function
at getStaticPaths (/vercel/path0/.next/server/pages/artists/[slug].js:106:24)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async buildStaticPaths (/vercel/path0/node_modules/next/dist/build/utils.js:498:31)
at async /vercel/path0/node_modules/next/dist/build/utils.js:641:119
at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:74:20) {
type: 'TypeError'
}
export async function getStaticProps({ params }) {
const siteSettings = await fetcher("http://localhost:3000/api/settings");
const artists = await fetcher(
`${process.env.URL}/api/artists/${params.slug}`
);
const artist = artists.allArtist[0];
return {
props: {
siteSettings,
artist,
},
};
}
export async function getStaticPaths() {
const artists = await fetch(`${process.env.URL}/api/artists`);
return {
paths: artists.map((artist) => {
return {
params: {
slug: artist.slug.current,
},
};
}),
fallback: false,
};
}
How would I go about fixing this error, as I said it works perfectly fine in the dev server with no console logs containing any errors.
Any help would be greatly appreciated.
I attempted writing the API route logic directly in the getStaticProps function and this fixed the error #juliomalves also posted this link which suggests a similar answer: Fetch error when building Next.js static website in production
Thanks for the help.
Mac

ExpoBarCodeScannerModule.scanFromURLAsync thrown an error

I'm trying to make a scanner in React Native that takes an image file, scans it and returns data that contains in barcode. I'm using a BarCodeScanner extension from Expo SDK.
It throws an error when I'm trying to use it.
Error looks like:
An exception was thrown while calling `ExpoBarCodeScannerModule.scanFromURLAsync` with arguments `(
1,
(
"org.iso.QRCode"
)
)`: -[__NSCFNumber length]: unrecognized selector sent to instance 0xe17787ebcc27c1d0
- node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:104:55 in <unknown>
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:414:4 in __invokeCallback
- ... 4 more stack frames from framework internals
My code where I'm trying to use extension method:
file = require('./assets/image.jpg');
componentDidMount(){
BarCodeScanner.scanFromURLAsync(this. file).then(data => {
console.log(data)
}).catch(err => {
console.log(err)
})
}
Do you have any thoughts what does it mean?
A bit too late, but for anyone with simmilar problem. You can use expo ImagePicker package to select image. It will return array of objects. One of the parameters of the object is URI of the image that can be used as an input to BarCodeScanner.scanFromURLAsync method.
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: false,
quality: 1,
});
if (!result.canceled) {
let decodedBarcodeImage = await BarCodeScanner.scanFromURLAsync(result.assets[0].uri);
// Handle result data
console.log(decodedBarcodeImage);
} else {
// Handle canceled result
console.log('You did not select any image.');
}
};

FCM Parsing error: Identifier 'functions' has already been declared

I'm learning FCM and I'm currently editing the index.js file to execute Firebase functions. However, when I deploy the function 'sendPushNotifications' I receive the error "Parsing error: Identifier 'functions' has already been declared." I've only declared it once within the file so I'm not sure if it's something beyond the file that I have to edit. I apologize for the poor formatting of the code below, I'm still not too used to pasting code into SO.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendPushNotifications = functions.https.onRequest((req,res) => {
response.send("Attempting to send push notification...")
console.log("LOGGER --- Trying to send push mesage")
var registrationToken = 'dSXeXBSHShU:APA91bFHWw_jNF1pr8Toq3OelqtyXrTZZssJW7YHMlP-tiNJ41uuO-pS--rfWduPFEEC72FchtDRHbt1RMM1e5kSWHUDVhWFvIAtx82LjIDiUNlmk14Ix_SLtrN_vB55rbr1tgcpS3CW';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
return response
})
.catch((error) => {
console.log('Error sending message:', error);
throw new Error("Error sending message");
});
})
got the same error.
Check your code, you might have declared the "const function" multiple time ;)

Javascript eslint error for require, export and console field

I have made a script for sending push notifications to my Firebase server, but javascript eslint is throwing error for const first.
Then I found on Google that I have to put ecmaVersion = 6 in my .eslintsrc file.
I did that then it is showing error on require, exports and console field.
I am using Atom as my compiler for code. This is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.printUrl = functions.database.ref('images/{uid}').onWrite(event => {
var request = event.data.val();
var payload = {
data:{
url : request.url,
location : request.location
}
};
admin.messaging().sendToTopic(request.topic, payload)
.then(function(response){
console.log("Successfully sent message : ", response);
})
.catch(function(error){
console.log("Error sending message : ", error);
})
});
You need to let eslint know that you're working in a Node environment to get rid of the require and exports errors. So by adding this to your eslintConfig:
"env": {
"node": true
}
In order to allow the console.log, you will have to turn on the rule by adding this to your eslintconfig:
"rules": {
"no-console": 0
}
You can find more information here: https://eslint.org/docs/user-guide/configuring

createkeysand certificate aws javascript

I am implementing the following code using javascript in browser to create certificate and key pair:
var iot = new AWS.Iot();
function createCert(){
var params = {
setAsActive:false
};
iot.createKeysAndCertificate(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
};
and I am getting the ERROR as :
UnknownOperationException: null
at Object.s [as extractError] (https://sdk.amazonaws.com/js/aws-sdk-2.106.0.min.js:42:24512)
at constructor.o (https://sdk.amazonaws.com/js/aws-sdk-2.106.0.min.js:42:29401)
Please help me in resolving this error.
Thank You
Seems like I had configured AWS for dynamoDB and the endpoint of AWS.Iot was not updated.
Now, it works!!!

Categories