-: It's a good practice to implement a slash me endpoint in
any API.
So, basically, an endpoint where a user can retrieve
his own data, all right?
And so, let's now, very quickly, implement that.
And so basically it's gonna be something very similar to
these updateme and deleteme endpoints that we
already have, right?
So, let's add export dot getme, all right?
Now, we still actually want to use the getOne
factory function, so basically, uh,
this one here, right?
Because otherwise it would be very, very
similar code to this one.
Now, the only problem with this is that getOne basically
uses the ID coming from the parameter in order to get the
requested document.
But, what we want to do now is to basically get the document
based on the current user ID,
so the ID coming from the currently logged in user, okay?
And so that way we don't have to pass in any ID as a URL
parameter, right?
So, how can we do that? Well, very simple.
All we will do here is a very simple middleware,
which is gonna go like this.
So as always, request, response, next,
and then all we're gonna do is to say request,
dot params, dot ID, which remember,
is what the getOne is going to use,
and tell it equal to request dot user dot ID.
And that's it!
All right?
And so we will then add this middleware here
before calling getOne.
So, let's implement that so user routes
and I'm going to add it right here.
So router dot get slash me,
and now, of course, we need to be logged in.
So protect, and this will then add the user to the
current request, which you already know will then allow
us to read the ID from that user, right?
Then, the next step is to then basically put that user ID
into the params dot ID. Okay?
So basically faking that the ID is actually coming
from the URL.
So, user controller, uh, dot getme,
and then finally user controller getuser.
Okay? Make sense?
Let's now very quickly test this out,
and so it's gonna be a bit similar to this.
But then, slash me.
Of course we need authorization. Okay?
And I'm also saving this in the users,
and to get current user.
Now, okay? Let's actually add it, these names
because they look different so they have this data here
for some reason.
Okay, this one doesn't but still it's wrong here.
All right? So let's now, just to make sure,
log in as this admin. All right?
And so now, get the data about this current user.
So nothing in the body, nothing in the URL,
but we still get the data about ourselves.
So, name, email, role, and really all the data
that there is about this user. Nice.
So, again, you saw the great power of middleware.
Where it was so easy to simply implement this getme
middleware, so that then after that we can use our
simple getuser.
So, that one coming from the factory function, right?
Okay, and that's it.
That's all we had to do for this small task.