百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
C

connect-rest

> 编程语言
开源

为连接 Node.js 提供了极具特色的 RESTful Web 服务中间件

99 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

为连接 Node.js 提供了极具特色的 RESTful Web 服务中间件

CONNECT-REST - Exceptionally featureful Restful web services middleware for connect / node.js

Open discussion at Discord

! 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 )

assign function

Other way to assign is to use the assign function directly.

Example:

javascript
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 )

Reflective assignement

See chapter for details: Reflective publishing

parameters

After each assign function you might need to pass the followings:

  • a path description
  • a function to be called.

Path description

connect-rest supports many options to be used as path description.

Of course simple paths can be defined as follows:

javascript
rest.get('/user/profile', asyncFunctionN0 )

But I guess you are interested in more complex solutions. Please, fing them below:

Regular expression

javascript
rest.get( /^\/[tT]([a-zA-Z]){4}$/g, asyncFunctionN0 )

This will match to URIs of '/api/tAbba' but won't to '/api/t1abcd8'.

Named parameters

javascript
rest.get('/books/:title', asyncFunctionN0 )

or

javascript
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:

javascript
{"headers": ...,"parameters":{"title":"AliceInWonderland", "chapter": "1"}}

Optional parameter

javascript
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

javascript
'/store'

or using

javascript
'/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'.

General matcher

javascript
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

javascript
'/inquire'

so can be called using

javascript
'/inquire/alice/in/wonderland'

or using

javascript
'/inquire/oz/the/great/wizard'

paths. This results to have the parameter 'book' with value

javascript
'alice/in/wonderland' or 'oz/the/great/wizard'

respectively.

You can make rather complex mixtures of those options as well:

javascript
'/borrow/:uid/?isbn/:bookTitle'

One can call this with uri:

javascript
'borrow/2/AliceInWonderland' or 'borrow/2/HG1232131/AliceInWonderland'

The character '*' can be used for both path and version too to make generic bindings:

javascript
{ path: '*', version: '*' }

Be aware, that this path will be matched to all paths within the defined context.

Range matcher

javascript
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.

Special assigns:

You can use the all options above at once.

javascript
[ { path: '/rent/:country/?isbn/*bookTitle', version: '=2.1.1' } ]

Just define what you really need. :)

Parameter processing

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.

Versioning

As for versioning, the syntax is semantic versioning, the same you use for npm

javascript
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"); } } );

Back to Feature list

API_KEY management

The option passed to the connect-rest might contain an array enumerating accepted api_keys:

javascript
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:

javascript
'/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

javascript
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.

Unprotected REST service

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:

javascript
rest.get( { path: '/special', unprotected: true }, asyncFunctionN0)

Protector

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.

javascript
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:

javascript
var options = {
	'context': '/api'
}
var rest = Rest.create( options )
connectApp.use( rest.processRequest() )

Default context is the '/api' string.

Orchestrating the contexts

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:

javascript
rest.get( { path: '/workspace', context: '/pages' }, asyncFunctionN0)

This REST function can be called by sending a GET request to the address of

/pages/workspace

This 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.

Discovery services

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.

javascript
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.0

would retrieve all services which can be called using version 3.0.0 (non-versioned and matching versioned services). The returned JSON is the following:

javascript
{
	"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.

Prototype services

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.

javascript
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:

javascript
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:

javascript
'/api/proto/POST/2.3.0/api/twist?api_key=849b7648-14b8-4154-9ef2-8d1dc4c2b7e9'

will retrieve the object

javascript
{'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.

Back to Feature list

Remove services

One can remove a published service by calling the following function:

javascript
rest.unpost( '/shake' )

That code removes all REST services which would be fired by calling with

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言