为连接 Node.js 提供了极具特色的 RESTful Web 服务中间件
CONNECT-REST - Exceptionally featureful Restful web services middleware for connect / node.js
! Note ! From version 3.0.0, connect-rest requires NodeJS 8.0.0 or higher and async/await based! For node =1.0.0' }, asyncFunctionN1 )
rest.post( [ '/act', '/do' ], asyncFunctionN2 )
rest.post( [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], asyncFunctionN3 )
__All service functions must be async!__
[Back to Feature list](#features)
## Assign
#### direct binding
You can assign your rest modules by specifying the needed _http_ request functions: __head, get, post, put, delete__.
Example:
```javascript
async function service( request, content ){
console.log( 'Received headers:' + JSON.stringify( request.headers ) )
console.log( 'Received parameters:' + JSON.stringify( request.parameters ) )
console.log( 'Received JSON object:' + JSON.stringify( content ) )
return 'ok'
}
rest.post( [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], service )Other way to assign is to use the assign function directly.
Example:
async function service( request, content ){
...
}
// bind the service funciont to all http request types
rest.assign( '*', [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], service )
...
// bind the service funciont to only the given http request types
rest.assign( ['head','get','post'], [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], service )See chapter for details: Reflective publishing
After each assign function you might need to pass the followings:
connect-rest supports many options to be used as path description.
Of course simple paths can be defined as follows:
rest.get('/user/profile', asyncFunctionN0 )But I guess you are interested in more complex solutions. Please, fing them below:
rest.get( /^\/[tT]([a-zA-Z]){4}$/g, asyncFunctionN0 )This will match to URIs of '/api/tAbba' but won't to '/api/t1abcd8'.
rest.get('/books/:title', asyncFunctionN0 )or
rest.get('/books/:title/:chapter', asyncFunctionN0 )You can define parametrized paths for services to accept REST variables from the caller. In this case, whatever string is after the 'books', will be interpret as variable(s) and passed to the service function via the request object.
So sending a get request to the uri '/api/books/AliceInWonderland/1', will result the following request object:
{"headers": ...,"parameters":{"title":"AliceInWonderland", "chapter": "1"}}rest.post('/store/?id', asyncFunctionN )This definition allows you to define one optional parameter at the end of the path. It might be called using
'/store'or using
'/store/108'paths. Both HTTP calls will be directed to the same functionN service. In latter case, the '108' will be set as a parameter in the request object with the value of '108'.
rest.get('/inquire/*book', asyncFunctionM )This definition gives you the possibility to define a general matcher allowing to have been called with anything after the string
'/inquire'so can be called using
'/inquire/alice/in/wonderland'or using
'/inquire/oz/the/great/wizard'paths. This results to have the parameter 'book' with value
'alice/in/wonderland' or 'oz/the/great/wizard'respectively.
You can make rather complex mixtures of those options as well:
'/borrow/:uid/?isbn/:bookTitle'One can call this with uri:
'borrow/2/AliceInWonderland' or 'borrow/2/HG1232131/AliceInWonderland'The character '*' can be used for both path and version too to make generic bindings:
{ path: '*', version: '*' }Be aware, that this path will be matched to all paths within the defined context.
rest.get( '/convert/@format', function( request, content ){
return 'ok'
}, { format:[ 'euro', 'usd', 'huf' ] } )This definition creates a rest service answering to GET requests if the format part of the URI is contained by the array in the option object. The character '@' tells the connect-rest to match the parameter 'format' to the array called by the same name.
By calling this service with the following URI '/api/convert/usd' will be executed, but calling with '/api/convert/gbp' no rest will be called and 404 will be returned.
You can use the all options above at once.
[ { path: '/rent/:country/?isbn/*bookTitle', version: '=2.1.1' } ]Just define what you really need. :)
The logic how connect-rest is managing parameter replacement is the following:
The parameters are processed in the path definition order and any missing optional parameter will be filled with empty strings to keep the order of them keeping in sight all mandatory parameters put after the optional ones.
As for versioning, the syntax is semantic versioning, the same you use for npm
rest.get( { path: '/special', version: '1.0.0' }, asyncFunctionN0)So you can use different version specificaiton depending on your need:
version: '1.0.0 - 2.9999.9999'
version: '2.0.1'
version: '2.x'
version: '~1'
version: '>=1.0.2 =2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], function( request, content ){
return JSON.stringify(content);
}, null, { contentType:'application/xml', validator: function(req, res){ return _.contains(req.user.roles, "superuser"); } } );The option passed to the connect-rest might contain an array enumerating accepted api_keys:
var options = {
'apiKeys': [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ]
...
}If property 'apiKeys' is present, the associated array of strings will be used as the list of api keys demanded regarding every incoming calls. So having such option, a call should look like this:
'/api/books/AliceInWonderland/1?api_key=849b7648-14b8-4154-9ef2-8d1dc4c2b7e9'otherwise error response will be sent with status code 401 claiming: 'API_KEY is required.'.
You can restrict access on service-level. When you call
rest.get( { path: '/shake', version: '>=2.0.0' }, async function( request, content ){
return 'OK'
}, { apiKeys:['1234-1234-1234-1234'] } )That will require to use the API_KEY '1234-1234-1234-1234' when call that REST service. This will help you refine your access control on service basis.
When you are using API_KEYs, you still might want to have 'exceptions'. Functions which can be served out of the border os API_KEY restriction. You can turn off that protection for a given service like this:
rest.get( { path: '/special', unprotected: true }, asyncFunctionN0)Protector is a function which can be passed when creating a rest services and decides if a given call is allowed or should be blocked and ignored. So the protector function called in every rest call when the given path is evaluated and matched and boolean return value of the function tells to the connect-rest to allow the rest function's execution to take place or blocked by some security reason.
rest.get( { path: '/special', protector: async function( req, res, pathname, path ){ return 'ok' } }, asyncFunctionN0);
…
javascript
rest.context( '/api' ) // means that every rest calls need to be sent to '/api/X' path.or through the option object as well when you add the middleware to the connect object:
var options = {
'context': '/api'
}
var rest = Rest.create( options )
connectApp.use( rest.processRequest() )Default context is the '/api' string.
The connect-rest also allows you to specify the context at REST function level. This helps if you want to orchestrate your functions using multiple contexts. Let me show you:
rest.get( { path: '/workspace', context: '/pages' }, asyncFunctionN0)This REST function can be called by sending a GET request to the address of
/pages/workspaceThis way you can easily manage dynamic templates not being forced to be in the same context as API calls.
You can orchestrate the contexts of your architecture as it pleases you.
connect-rest provides a built-in service: discover. Via a simple get request, it allows you - by specifying a version - to discover the plublished REST apis matching the given version.
var options = {
'discover: { path': 'discover', secure: true }
}
var rest = Rest.create( options )
connectApp.use( rest.processRequest() )This will enable this service - considering the context described above - on the path '/api/discover/:version'. Sending a get request to - let's say - this path
http://localhost:8080/api/discover/3.0.0would retrieve all services which can be called using version 3.0.0 (non-versioned and matching versioned services). The returned JSON is the following:
{
"HEAD":["/peek"],
"GET":["discover/:version","/books/:title/:chapter"],
"POST":["/store",{"path":"/make","version":">=1.0.0"},"/act","/do",{"path":"/shake","version":">=2.0.0"},{"path":"/twist","version":">=2.1.1"}],
"PUT":[],
"DELETE":[]
}The option secure tells connect-rest if security should be active for this service.
The assign-methods allows you to set an extra object in the third parameter. An object which can be considered as a prototype of the expected parameter of the service when a client wants to make a call.
rest.post( [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], asyncFunctionN, { prototypeObject: {'title': 'Alice in Wonderland'} } )That parameter debriefs the client what structure the functionN expects to receive. To activate this feature, first you have to add a new attribute to the options object:
var options = {
'apiKeys': [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],
'proto: { path': 'proto', secure: true },
'logger': 'connect-rest'
}This 'proto' object tells connect-rest that the given path is accepting requests to retrieve prototypes:
'/api/proto/POST/2.3.0/api/twist?api_key=849b7648-14b8-4154-9ef2-8d1dc4c2b7e9'will retrieve the object
{'title': 'Alice in Wonderland'}because the service
on path '/api/twist' and method 'POST' with version '2.3.0'can be called and there is an assigned prototype object to it. Giving access method, version and path is mandatory for this feature.
The option secure tells connect-rest if security should be active for this service.
One can remove a published service by calling the following function:
rest.unpost( '/shake' )That code removes all REST services which would be fired by calling with
暂无开放 Issues,或尚未同步最近议题。