Endpoints¶
Each Endpoint
represents a single URI and can support any
number of the following HTTP operations: GET
, POST
, PUT
, PATCH
,
DELETE
, HEAD
, and OPTIONS
.
Simple Endpoints¶
Below is a simple Endpoint
at the path /hello
that
defines two operations, get
and post
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
endpoints: {
// Endpoint definitions go here
hello: o({
_type: carbon.carbond.Endpoint,
get: function(req) {
return {msg: "Hello World!"}
},
post: function(req) {
return {msg: req.body.msg}
}
})
}
})
})
|
Endpoints with named path parameters¶
Endpoint
s can be defined using paths with named
parameters. Bound template variables values can then be accessed via
req.params
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
dbUri: 'mongodb://localhost:27017/mydb',
endpoints: {
'users': o({
_type: carbon.carbond.Endpoint,
get: function(req) {
// get all users
return getUsers()
}
}),
'users/:id': o({
_type: carbon.carbond.Endpoint,
get: function(req) {
// get the user
return getUserById(req.params.id)
},
delete: function(req) {
// delete the user
deleteUser(req.params.id)
return null
}
})
}
})
})
|
In this example, a request for the path /users/jonny16
will route to the
/users/:id
Endpoint
and req.params will
have the value "jonny16"
.
Sub-endpoints¶
Endpoints
s may contain sub-endpoints. Here is an example that is
similar to the API as above, but that uses a sub-endpoint to define an
Endpoint
at the path /users/:id
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
name: 'foo',
dbUri: 'mongodb://localhost:27017/mydb',
endpoints: {
'users': o({
_type: carbon.carbond.Endpoint,
get: function(req) {
// get all users
return getUsers()
},
endpoints: {
':id': o({
_type: carbon.carbond.Endpoint,
get: function(req) {
// get the user
return getUserById(req.params.id)
},
delete: function(req) {
// delete the user
deleteUser(req.params.id)
return null
}
})
}
})
}
})
})
|
Accessing Service properties from within Endpoints¶
Properties of the top-level Service
can be accessed via the
getService
property of your Endpoint
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
endpoints: {
status: o({
_type: carbon.carbond.Endpoint,
get: function(req) {
return {
running: true,
msg: "Up and running on port: " + this.getService().port
}
}
})
}
})
})
|