Optional route pieces (not only parameter)


#1

Hello guys, how r u doing?

I’m trying to realize, how can i create a route with optional pieces, not only parameters, or without having to create 2 routes for the same method.
Eg.

...
Route.get('/categories/page/:page?', 'ContentController@categories').as('categories.index')
...

So, if the visitor specify which page he wants to see, i’ll serve the correct paginated content for him, else, i’ll serve the first page of the listing, which can be done as the following.

...
Route.get('/categories', 'ContentController@categories').as('categories.index')
...

Is there any way to do this using AdonisJS built-in functions?


#2

Nope, these are 2 different routes and cannot be defined as one


#3

You could avoid creating two routes if instead of the pagination page being a route param it gets appended as a get param…

/categories?page=2 instead of /categories/page/2

In this case only your second defined route from your initial post would be defined, your paginator rendered to the page will need to generate the appropriate links with get parameters as shown above…

That get parameter ?page is still available in the request object as page so then you can just tack this on to your query that’s running on that controller and it’ll either show page 1, or whatever other page is specified in that get parameter…

.paginate(request.input('page', 1), request.input('perPage', 10))

That’ll also allow you to optionally pass a ‘perPage’ param to change the pagination size dynamically :slight_smile:


#4

I was looking for a solution different of this, but just for curiosity, to see what is possible to do with the adonis router module.

Your solution is what i figured out when i was building my pagination methods.

And, just for improve your solution, instead of using request.input('page', 1) i’ve created a middleware which catches these variables from request and attach to a paginate property in the context object, so within my controller i can just do this

async method({request, response, pagination})
{
   const data = await Mymodel.query().paginate(pagination.page, pagination.perPage)
   ...
}

#5

I don’t know that this necessarily saves you all that much effort, or that it’s necessarily an improvement, but there are multiple ways to solve most problems :slight_smile:


#6

inside my middleware file i have sanitized the request inputs, just for prevent injection attacks.

my friend and me are working on a POC of injection attacks in node.js apps and this has proved which we must take care of all user inputs which are processed by the server.

thus, i’m feeling more secure inspecting and sanitizing all the data i pass to lucid.