Reputation: 153
I'm trying to make a chat app using the following Components (i just write everything here, because I don't know which information are important, sorry): Angular, Nodejs, Expressjs, MongoDB, Mongoose
I have multiple DB entries for localhost:3000/message
in the schema of [{content: "this is a message(text)", sender: "1337(number)", receiver:"42(number)"}]
Now i want to display in my angular page only the entries where the current user (via his by mongo generated ID) is either a sender of receiver (so basically the messages he is alowed to see).
Of course i canrequest all messages and then filter them in my frontend, but this seems to me like bad practice and a massive security issue if i want to put the page online and everyone can request all the messages if they find the api.
A different approach I thought of is making a route to /message/:userID
where his messages are stored. This may conflict with /message/:messageID
where you can put/delete a single massage. This is not very likely but very problematic if it occurs
What shall I choose and how to do it or is there a mighty tool/practice that i didn't find yet?
Thank you in advance
Upvotes: 0
Views: 3752
Reputation: 3625
I would definitely let mongoose do a query to only get the documents you need - it's easier and more secure to let the server do this rather then do the sorting/filtering in the frontend. I assume you know about the mongoose queries and only focusing on your endpoint problem.
When I work with Express and API Endpoints I try to make them as clear as possible. In your example I would implement the following routes. In this case I assume you are using JWT Tokens to authenticate the user.
Get a specific message from the message pool
app.get('/messages/:id')
Get all messages from the message pool
app.get('/messages')
app.get('/user/messages/:id')
app.get('/user/messages')
Other then that, if you use various available HTTP Request Types, like PUT
and DELETE
you can get even more diversion.
app.delete('/user/messages/:id')
app.put('/user/messages/:id')
I kind of depends on how you authenticate the user, and how the user object/information will be available in the request. Include the user id in the request body ? Use passport
and JWT Token to retrieve the user object in a middleware ? Many possibilities.
Upvotes: 2
Reputation: 491
You have three options.
GET /message/:id?action=<the_action_you_have_to_do ex: delete/get_messages>
app.get('/message/:id', (req, res) => {
req.query.action === 'delete'
// perform delete functions
req.query.action === 'get_messages'
// retrive messages
})
app.get('user/message/:id', (req, res) => {
// perform delete functions
})
app.get('/message/:id', (req, res) => {
// retrive messages
})
Upvotes: 2