Reputation: 483
I have two endpoints:
GET all users by ID
http.get(API_URL + "users/" + id)
GET all users by username
http.get(API_URL + "users/" + username)
Can I send different parameters on a same route:
router.get("/users/:id", async ctx => {
//ctx.request.param is id
//do something
});
router.get("/users/:username", async ctx => {
//ctx.request.param is username
//do something
});
Thanks for your help!
Upvotes: 0
Views: 994
Reputation: 441
short answer is no.
I think the good solution maybe, your route setup like this
GET /users?<your query here>
then your can query your users with <your query>.id
or query>.username
Upvotes: 0
Reputation: 2781
In your example, you are providing URL parameters, not (named) query parameters, so it is just a part of the URL, so this is anyway "just a string".
This means, that koa router would then be aware of data types (e.g. integer
for :id
and string
for :name
). This is - as far as I know - not the case.
When you have
"/users/:id"
or
"/users/:username"
you just give this part of the URL string a name - nothing more. (ctx.params.id OR ctx.params.username)
So you need to implement a logic, where you determine if the parameter is an integer (and handle is as an ID) or not (in which case you handle it as a username).
This could look like that:
router.get("/users/:id", async ctx => {
//ctx.request.id
if (!isNaN(ctx.request.id)) // it IS a number {
//do something with user ID
} else {
//do something with username
}
});
hope that makes sense ... otherwise, you really have to create two routes with a distingiashable signature
Upvotes: 2