Firebase Database query for http trigger - javascript

I'm trying to query my firebase realtime database for the list of User objects. I have a favourites field and in it I'm storing a list of id's of favourited users. How would I go about writing a http endpoint with cloud functions so that it returns a json list of User objects corresponding to these ids in database?
Thanks a lot.

You can configure your development environment for FCF by following this. Once you've initialized your project, write a function inside functions/index.js like this one:
exports.getFavouriteUsers = functions.https.onRequest((req, res) => {
var favouriteUsers = admin.database.ref('users/favourites').val();
res.status(200).send(favouriteUsers);
});
Finally deploy and you'll be able to make requests to the endpoint shown in the console.
Look at this documentation for HTTP triggers

Related

how we save logs of our application actions in mongodb(node.js) with one schema and limited information

I am working on a node js with MongoDB database we want to logs of our application action with limited information like success, action name, user id, time, etc so how we can do this in node js with MongoDB
You can look in the official website of mongo how to do it Mongo Logs, and if you want a custom one just create a new db/collection to put in your logs and send it as a regular request.

Firebase Cloud Firestore: Managing indexes from code

I am trying to migrate from Firebase Real time Database to Cloud Firestore in order to use "complex" queries among collections but I found some "issues" that I don't know how to solve.
My server uses Express JS and Firebase Admin SDK. I am trying to create a CRUD router for my admin dashboard but I am getting the following error:
"9 FAILED_PRECONDITION: The query requires an index. You can create it here: ...
When I access that URL (...) I get some error I don't have enough permissions... Well, anyway, after some research I understood that "complex" queries requires indexes and they have to be more than one.
This is my current router code so you can see what I want to achieve:
// GET - Get users
router.get('/', async (req: Request, res: Response) => {
...
let ref: any = db.collection('users').orderBy('createdAt');
Object.keys(req.query).forEach(key => {
ref = ref.where(key, '==', req.query[key]);
});
...
});
As you can see when I iterate req.query key I am adding a conditional statement to the query. My idea is to progamatically add custom filters from the client.
According to what I understood from documentation, I should create a complex index type for every document property.
Therefore, what should I do in order to achieve the mentioned idea? Thanks in advance.
Firestore compound queries have some limitations.
One is that to use more than one method, for example "where" and "orderBy", you need to create an index for this query.
So in your case, as your queries are dynamic, for each query you will have to create an index.
My suggestion is that you only use the "where" in your queries and in the other filters use javascript to filter. Or migrate to another database like MongoDB.
This is the link to the Firestore documentation explaining the compound queries: https://firebase.google.com/docs/firestore/query-data/queries?hl=en-us

How to handle multiple tabs using in firebase using realtime database

I am creating a multiplayer game website. I am using three features of firebase.
Firebase authentication
Firestore
Real time database
The data which is permanent is stored in firestore. Like profile image, username etc. The data in firestore is stored in collection users and the key is same as the authentication id which we get from user.uid
The second data is temporary data which contains the chat messages and current game situation and player turn etc. This data is stored in real time database.
There are two base objects in real time data base. One is rooms and other is users. When a user logs in to website the permanent data is taken from the firestore and placed with temporary data(because we might need to display the permanent data again and again). The function I am using to get permanent data and create combination with temp data is
//'uid' is the permanent id which is used in firestore and also in authentication.
export const addUser = async (uid: string) => {
//gets the permanent data from firestore
const data = await getUserData(uid);
//Set it to realtime database my adding one more temp prop
return await dbUsers.child(uid).set({...data, messages: []});
};
Till now everything is fine problem comes when I have to remove the user on disconnection. I used t
export const removeUser = async (uid: string) => {
return await dbUsers.child(uid).remove();
};
The above way doesn't work for multiple tabs. Consider if user had opened multiple tabs and he just closed one server then realtime database will consider it logged out.
Do I need to create realtime data on the basis of another id using push() method. Kindly guide me to correct path.
If I understand correctly you're trying to track the user's online status using Firebase's onDisconnect handlers. To do this:
You write a value for the user's UID when they connect.
You then delete that value using an onDisconnect handler.
This indeed will not work when the user opens the app in multiple locations (tabs, browsers, or devices). The reason is that a user can be online in multiple locations, and your code and data structure needs to cater for this.
The idiomatic approach is the one outlined in the sample presence app in the Firebase documentation, and works with a data structure like this:
"OnlineUsers": {
"uidOfUser1": {
"-LKeyOfConnection1": true,
"-LKeyOfConnection2": true
},
"uidOfUser2": {
"-LKeyOfConnection3": true,
"-LKeyOfConnection4": true
}
}
In this structure, if a user has two open connections (on different tabs, browsers, devices), they have two nodes under their UID, each with its own onDisconnect handler. When both connections are closed, with connection keys disappear, and thus their /OnlineUsers/$uid node also disappears automatically.
So to detect if a user is online in the above structure, you'd check if there is a node under /OnlineUsers with their UID.

HTTP Request - Delete JSON file key in Firebase with Axios

I have a firebase database setup with an orders.json file created. I already have it setup to where I can post an order to the json file from a javascript project, and then firebase assigns a unique key which looks like "-LKx1RmbvyruM8-5S2mo". I would like to delete a single order based off of that unique identifier key via http request and query params without deleting the entire orders.json file. I'm also using authentication, so my request would look like this:
axios.delete('https://myproject-37b7d.firebaseio.com/orders.json?auth=mytoken')
This would of course delete the entire json file which I do not want. Would I put the unique key in the url query params somehow? Or in the axios config? I figured out how to console log it in a GET request via the .get().then(res => console.log(res.data["-LKx1RmbvyruM8-5S2mo"]))
I tried reading through firebase's api and not many good examples. Any help is much appreciated]1
u
Due to firebase database is a simple json-like object, and single order is an object too, with its own link, I simply make a delete request like that:
removeOrderHandler = (orderId) =>{
axios.delete("/orders/" + orderId +".json?auth=" + this.props.token)

creating user using AWS cognito identity

I am learning to create a serverless API server using AWS lambda, dynamodb, cogito sync. It was going well until I got confused with users table.
So basically, I am trying to make twitter clone API. So as user I should be able to create post, follow another users etc.
Signup and Signin are successfully handled by Cognito Identity, the problem is how do I access the Users data on the cognito? A user can have following and followers attributes which contains other users ID.
What I did currently, on the app I register using cognito identity then I will make another call to the API gateway to create a user on dynamodb. So basically there are two separate users data. I am not sure if this is the correct way to do this.
Should I make a call on cognito on the backend instead on the app? Should i have separate users table for this?
Example Front End code on ionic
$scope.signup = function() {
$ionicLoading.show({
template: 'Registering user...'
});
// this is the factory for signing up
awsCognitoIdentityFactory.signUp($scope.user.email, $scope.user.name, $scope.user.email, $scope.user.password,
function(err, result) {
if (err) {
errorHandler(err);
return false;
}
// creating user on the api
User.create($scope.user).then(function(response) {
console.log(response);
});
// store locally
store.set('user', $scope.user);
$ionicLoading.hide();
$scope.$apply();
$scope.user = {}; //clear register form
$state.go('confirmation');
});
return true;
};
It sounds like you're using Cognito User Pools, in which case you can use the GetUser API. Given context for the user, it will return all attributes stored against that user.
I can't comment on the best way to store user metadata as it will vary greatly based on the specifics and needs of your app, but it's probably worth reading up on Cognito's system of custom attributes, which lets you store custom data against users. These can be configured/added from the Cognito console.

Categories

Resources