Routing is one of the main concepts in back-end development. It is how we set addresses for our API endpoints. Silvie
utilizes the power of
Method Decorators to set an address for a method in a controller. This is meant to be as simple
Route decorator is how you define your routes and attach them to your request handlers. It can be imported from the main
controller file located at
The route decorator will take two parameters:
The method needs to be a string with the name of one of the methods mentioned in HTTP Methods.
As you may already know, the decorators are some functions written before something to add a functionality to it, and
they are marked with
The above code sample will attach the
greeter method of
GreetingController class to a
/say-hi URL accessible by
Silvie has an underlying express server to handle HTTP requests. Therefore, the available HTTP verbs are:
- Official Verbs
- Unofficial Verbs
There is also an
ALL method, which can be used to respond to all request types from a request handler. It is just like
you mount a middleware on that specific path. So there won't be a specific HTTP Verb attached to your request handler.
Note that all verbs mentioned above can also be used in lowercase, or any other case you may like. They will convert to lowercase when they are being registered.
Basic Routes are some usual URLs without any parameters.
Wildcard routes add more flexibility to your application routes.
Using a question mark after a character or after a group of characters will make that part optional.
Using a plus sign after a character, will match URLs containing one or more of that character there.
Using an astrix sign after a character, will match URLs containing zero or more of that character there.
Note that unlike the
* won't work for character groups.
There is also another usage of
* operator which you can wildcard the whole route. This can be done by putting an
astrix sign at the end of a routes trailing slash. The wildcard path that was matched using the
* sign, will be
You may pass a regular expression as the url to the route decorator for handling more advanced routes.
It is sometimes necessary to define parameters in the URL. There are multiple types of parameters which you can specify in a URL string.
A basic route parameters is a name identified with a
You can make it optional with
? sign after the parameter name.
It there was a
postId parameter in the url, will return with a post with a specific id. Otherwise, it will return all
posts as the result.
You may also need more control over the parameters you define in the URL. So you can append a regular expression wrapped in a pair of parentheses.
This route will only respond to those request with a
postId that has 3 or more digits.