Firestore Data not getting uploaded to Algolia - reactjs

I am facing a problem of uploading data(records) from firebase firestore to Algolia database. I am using the Algolia API to upload data.
Here is the code of my index.js(code for uploading data from firestore into Algolia)-
// Import all needed modules.
const functions=require("firebase-functions");
const admin=require("firebase-admin");
const algoliasearch=require("algoliasearch");
// Set up Firestore.
admin.initializeApp();
const db = admin.firestore();
const env=functions.config();
// Set up Algolia.
const client = algoliasearch(env.algolia.appid, env.algolia.apikey);
const index = client.initIndex("users");
// Create a HTTP request cloud function.
async function sendCollectionToAlgolia() {
// This array will contain all records to be indexed in Algolia.
var algoliaRecords = [];
const querySnapshot = await db.collection('users').get();
querySnapshot.docs.forEach(doc => {
const document = doc.data();
const record = {
objectID: doc.id,
name: document.name,
age: document.age,
gender: document.gender,
certificate: document.certificate,
about: document.about,
interestedIn: document.interestedIn,
isVerified: document.isVerified,
joinDate: document.joinDate,
level: document.level,
location: document.location,
meetups: document.meetups,
geoHash: document.geoHash,
height: document.height,
photoUrl: document.photoUrl,
points: document.points,
preferredBuddyFitnessLevel: document.preferredBuddyFitnessLevel,
uid: document.uid,
weight: document.weight,
userFitnessLevel: document.userFitnessLevel
};
algoliaRecords.push(record);
});
// After all records are created, we save them to
index.saveObjects(algoliaRecords,{ autoGenerateObjectIDIfNotExist: true })
.then(objects =>{console.log(objects.firstname);})
.catch(err=>{console.log(err);})
}
module.exports=sendCollectionToAlgolia;
Now after I execute firebase deploy --only functions:sendCollectionToAlgolia command in my terminal:
This is the output I get-Terminal Output
It is saying that the deployement is complete and successful but the data is not getting uploaded to my Algolia Dashboard
This is my Algolia dashboard-
Algolia Dashboard
Here the data is not visible.
Help will be appreciated!
Thanks in advance.

Related

`S3Client.send()` doesn't return `VersionId`

I have a bucket which has versioning enabled. In my ReactJS app, I need to upload files to the bucket and receive the new object metadata. I use S3 Client with PutObjectCommand to do the upload. The documentation here states:
Versioning
If you enable versioning for a bucket, Amazon S3 automatically generates a unique version ID for the object being stored. Amazon S3 returns this ID in the response. When you enable versioning for a bucket, if Amazon S3 receives multiple write requests for the same object simultaneously, it stores all of the objects.
So, I expect to receive a VersionId. But not only this field is undefined, but also other fields like requestId or `cfId.
Here is my module code:
import {
PutObjectCommand,
S3Client
} from '#aws-sdk/client-s3';
const S3_BUCKET_NAME = process.env.S3_BUCKET_NAME;
const AWS_REGION = process.env.AWS_REGION;
const AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY;
const AWS_SECRET_KEY = process.env.AWS_SECRET_KEY;
const client = new S3Client({
region: AWS_REGION,
credentials: {
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_KEY
}
});
const uploadToS3 = async function (fileToUpload) {
const data = await fileToUpload.arrayBuffer();
const params = {
Bucket: S3_BUCKET_NAME,
Key: fileToUpload.name,
Body: data
};
const command = new PutObjectCommand(params);
const result = await client.send(command);
console.log(result); // requestId: undefined, extendedRequestId: undefined, cfId: undefined
console.log(`VersionId: ${result.VersionId}`); // VersionId: undefined
}
export default {
uploadToS3
}
Have I missed anything here?

Problem with listening to messages OnSnapshot with a React Native Firebase Messaging App

I'm trying to create a React Native messaging app with the firebase SDK. In the chat screen I am trying to listen to updated messages in my firestore database. I'm following a lot of the code shown in this github repository https://github.com/ReactNativeSchool/react-native-firebase-chat-app, but it uses react-native-firebase and I am using the SDK which is causing making it hard for me to find the equivalent code with the firebase SDK. What am I doing wrong in the below code that is giving me the following error when I open the screen:
undefined is not a function (near '...(0,_firebaseConfig.listenToMessages)(threadID).onSnapshot...')
I believe it has to do with me not converting from react-native-firebase to the firebase SDK correctly, but I'm not sure.
Below is my listenToThreads code from the firebaseConfig file where I do all my firebase functions. Below that is the part I commented out that returned the values within that collection.
export const listenToMessages = async (threadID) => {
return firebase.firestore()
.collection('threads')
.doc(threadID)
.collection('messages');
// try {
// const q = query(collection(db, "threads"), where("tid", "==", threadID));
// const doc = await getDocs(q);
// const data = doc.docs[0].data();
// return data.messages;
// } catch {
// return [];
// }
};
and here is my onSnapshot code which I'm running inside a working UseFocusEffect hook.
const unsubscribe = listenToMessages(threadID).onSnapshot(
querySnapshot => {
const formattedMessages = querySnapshot.docs.map(doc => {
return {
_id: doc.id,
text: '',
createdAt: new Date().getTime(),
user: {}
};
});
setMessages(formattedMessages);
},
);
return () => {
unsubscribe();
};
The listenToMessages function should not be async.
It returns a promise rather than the doc you want. ✌️

How to get data from Google cloud storage

I use google cloud storage in my react project.
I am interested how to set another info of image to the object? for example: name, id etc.
before your advaces, I've used firebase firstore for img infos and after getting datas, creating one full object includes cloud files and firestore infos. BUT...
when I am getting files data in useEffect and want to set him info i have some undefined find item.
firstly when I render page, console parsedGallery returns array of objects.
console.log(item.name) returns item.name
console.log(obg) returns undefined !!!
when one more time refresh page everything getting ok
why happens this? what a problem?
please help me to correct this code or advice me new better way to get from cloud with clean code.
const listRef = ref(storage, `image/${currentUser?.uid}/gallery/`);
const galleryListFirestore = useSelector((state) => state.storeMain.gallery);
let parsedGallery;
if (galleryListFirestore?.length > 0) {
parsedGallery = JSON.parse(galleryListFirestore);
}
console.log(parsedGallery);
const [gallery, setGallery] = React.useState([]);
React.useEffect(() => {
listAll(listRef).then((response) => {
let galleria = [];
response?.items.forEach((item) => {
const obj = parsedGallery?.find((it) => it?.id == item?.name);
console.log(item.name);
console.log(obj);
getDownloadURL(item).then((url) => {
setGallery((prev) => [
...prev,
{
url: url,
id: obj?.id,
name: obj?.name,
uploadTime: obj?.addTime.seconds,
likes: obj?.likes,
post: obj?.post,
},
]);
});
});
setGallery(galleria);
});
}, []);

Getting data from database to set dynamic routes in getStaticMap method Next.js

In Next.js we have a feature of dynamic routing configuration on getStaticPaths method. I need to fetch the data from database based on that data, I need to set dynamic routes. But when ever I try to make a database call, I am getting an error mentioned below.
export async function getStaticPaths() {
const client = await MongoClient.connect('connection string');
const dataBase = client.db();
const collections = dataBase.collection('table name');
let result = await collections .find({}, { id: 1 }).toArray();
client.close();
let paths = result.map((data) => ({
params: { id: data.id.toString() }
}));
console.log(paths);
return {
fallback: false,
paths: paths
};
}
error that I can see,
./node_modules/mongodb/lib/url_parser.js:7:0
Module not found: Can't resolve 'dns'
Please help. Thanks in advance.

How to fetch data from external API and get it into Next.JS?

In React, NextJS, following the excellent Leigh Halliday YouTube tutorial: https://www.youtube.com/watch?v=_HOp7hBEjp8 ,
I want to fetch my data from an external API, instead of having hardcoded local JSON (file src/data.ts )like him:
export const data = {
bio: {
name: "FirstName Surname",
tagline: "Developer",
.
.
}
I'm trying to do something like this (replaces the hardcoded content in src/data.ts):
export const data = async () => {
const res = await fetch ('https://api...link');
console.log('in fetch: res: ' + res);
return res.json();
};
This fetch fails badly, I can see from the browser developer panel. I never see the console log message, but I can see there is something with the fetch. Any ideas?
UPDATE: This is the error message:
name: graphql, status: 400, type: fetch, initiator: createHttpLink.js: 76

Resources