-
Notifications
You must be signed in to change notification settings - Fork 1
Routing
Sys-API offers various ways of routing.
A route can be simple or complex.
This is a simple route:
api.get('/hello', "Hello World")
#=> {"response":"Hello World"}
As you can see the response is handled internally for you.
If you wish to access the router-object, you must pass an anonymous function. You can also pass middleware.
A router-object holds the req, res, next
methods of your route. There also is an additional method called send
.
More about that later.
Let's say you want to access the res
method of your route. This can be easily archived by calling obj.res
:
api.get('/hello', (router) ->
router.res.send("Hello World")
return router.next()
)
#=> "Hello World"
Access query-params:
api.get('/hello/:user', (router) ->
user = router.req.params.user
router.res.send(user)
return router.next()
)
#=> "The value you entered"
Access body-params:
api.post('/hello', (router) ->
user = router.req.body.user
router.send(user)
return router.next()
)
#=> "The value you entered"
You can use an unified response-property for all your responses. That way, your api-clients (applications, scripts ..) can listen to a specific name. It also makes your code more structured and you don't need to call obj.next()
. This is all done internally for you.
Every data that goes through obj.send
will be prefixed by {"response": your_data }
api.get('/hello', (router) ->
router.send("Hello World")
)
#=> {"response":"Hello World"}
The same applies if you just pass a string:
api.get('/hello', "Hello World")
#=> {"response":"Hello World"}
Access query-params:
api.get('/hello/:user', (router) ->
router.send(router.req.params.user)
)
#=> {"response": "The value you entered"}
Access body-params:
api.post('/hello', (router) ->
router.send(router.req.body.user)
)
#=> {"response": "The value you entered"}
You can use an object as well:
api.get({ url: '/hello' }, "Hello World")
#=> {"response":"Hello World"}
OR
Let's say you want to query a list of system-users. You can use the integrated "os" addon for that.
There are many ways on how this can be archived.
api.get('/users', (router) ->
api.os.users.all((err, users) ->
router.res.send(users)
router.next()
)
)
api.get('/users', (router) ->
api.os.users.all((err, users) -> router.send(users))
)
api.os.users.all((err, users) -> api.get('/users', users))
Cool, isn't it?
Addons