{"id":13671566,"url":"https://github.com/imrefazekas/connect-rest","last_synced_at":"2025-04-07T15:06:34.018Z","repository":{"id":6979895,"uuid":"8234611","full_name":"imrefazekas/connect-rest","owner":"imrefazekas","description":"Exceptionally featureful Restful web services middleware for connect node.js","archived":false,"fork":false,"pushed_at":"2020-07-16T21:05:16.000Z","size":643,"stargazers_count":100,"open_issues_count":5,"forks_count":29,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-04-14T16:28:29.929Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/imrefazekas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-02-16T10:51:12.000Z","updated_at":"2022-11-28T03:10:49.000Z","dependencies_parsed_at":"2022-09-12T22:51:22.012Z","dependency_job_id":null,"html_url":"https://github.com/imrefazekas/connect-rest","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imrefazekas%2Fconnect-rest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imrefazekas%2Fconnect-rest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imrefazekas%2Fconnect-rest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imrefazekas%2Fconnect-rest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/imrefazekas","download_url":"https://codeload.github.com/imrefazekas/connect-rest/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247675597,"owners_count":20977376,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T09:01:13.422Z","updated_at":"2025-04-07T15:06:33.988Z","avatar_url":"https://github.com/imrefazekas.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"CONNECT-REST - Exceptionally featureful Restful web services middleware for connect / node.js\n\n[Open discussion at Discord](https://discord.gg/pjHUaMU)\n\n[![npm version](https://badge.fury.io/js/connect-rest.svg)](http://badge.fury.io/js/connect-rest)\n [![Code Climate](https://codeclimate.com/github/imrefazekas/connect-rest/badges/gpa.svg)](https://codeclimate.com/github/imrefazekas/connect-rest)\n\n__! Note !__ From version 3.0.0, [connect-rest](https://github.com/imrefazekas/connect-rest) requires NodeJS 8.0.0 or higher and async/await based! For node \u003c8.0.0 please use older version of the lib.\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\n========\n\n[connect-rest](https://github.com/imrefazekas/connect-rest) is a featureful very easy-to-use middleware for [connect](http://www.senchalabs.org/connect/) for building REST APIs. The library has a stunning feature list beyond basic rest functionality.\n\nJust a few examples: (far from incomplete):\n- __execution branches__: a single service can have multiple paths and handlers\n- __versioning__: rest services can be versioned via many ways\n- __regular expressions__: path description can be given using regular expression\n- __parameter mappings__: path matchings can be bound as parameters\n- __proxy services__: proxying incoming requests to a remote point passing parameters, headers as you request\n- __service discovery__: built-in rest service allowing one to discover what rest services are available in general or for a given version\n- __\"reflective\" publishing__: by providing a single object, its methods will be published as rest services automatically by simple logic\n- __dynamic API protection__ by Protectors\n- __Multiple contexts__ for flexible orchestrating\n- __customizable HTTP-layer management__: HTTP status code, mime-types, headers, minifying can be set at service and execution level\n- __async services__: a rest service can call back asynchronously when the answer is made\n- __multiple return format__: handlers may return with strings, objects, streams and buffers, connect-rest will manage them adequately.\n\n\n__!Note__: connect-rest's concept is to provide a feature-full high-level connect middleware for your rest services carrying __only about content and business logic__, nothing else. However, in case of need for interoperability, the need might cause you to use only the path-related features alone. This can be done using [dispatchers](#dispatchers).\n\n# Usage\n\nThe [connect-rest](https://github.com/imrefazekas/connect-rest) is a simple, yet powerful middleware for [connect](http://www.senchalabs.org/connect/), inspired by [restify](http://mcavage.github.com/node-restify/).\nThe aim is to give a really feature-rich tool allowing you to focus on the business logic only.\n\n\n# Installation\n\n\t$ npm install connect-rest\n\n## Features:\n- [Quick setup](#quick-setup)\n- [Assign](#assign)\n- [Path description](#path-description)\n- [Versioning](#versioning)\n- [Rest functions](#rest-functions)\n- [Proxy rest services](#proxy-rest-services)\n- [Customize HTTP response](#customize-http-response)\n- [Customize answers of REST functions](#customize-answers-of-rest-functions)\n- [API_KEY management](#api_key-management)\n- [Unprotected rest service](#unprotected-rest-service)\n- [Protector](#protector)\n- [Context](#context)\n- [Orchestrating the contexts](#orchestrating-the-contexts)\n- [Discover services](#discover-services)\n- [Prototype services](#prototype-services)\n- [Remove services](#remove-services)\n- [Logging](#logging)\n- [Reflective publishing](#reflective-publishing)\n- [Domain support](#domain-support)\n- [Answering async rest requests](#answering-async-rest-requests)\n- [Dispatchers](#dispatchers)\n- [More examples](#more-examples)\n- [License](#license)\n- [Changelog](#changelog)\n\n\n## Quick setup\n```javascript\n// requires connect and connect-rest middleware\nvar connect = require('connect'),\nbodyParser = require('body-parser')\n\nvar Rest = require('connect-rest')\n\n// sets up connect and adds other middlewares to parse query, parameters, content and session\n// use the ones you need\nvar connectApp = connect()\n\t.use( bodyParser.urlencoded( { extended: true } ) )\n\t.use( bodyParser.json() )\n\n// initial configuration of connect-rest. all-of-them are optional.\n// default context is /api, all services are off by default\nvar options = {\n\tcontext: '/api',\n\tlogger:{ file: 'mochaTest.log', level: 'debug' },\n\tapiKeys: [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],\n\t// discover: { path: 'discover', secure: true },\n\t// proto: { path: 'proto', secure: true }\n}\nvar rest = Rest.create( options )\n\n// adds connect-rest middleware to connect\nconnectApp.use( rest.processRequest() )\n\n// defines a few sample rest services\nrest.get('/books/:title/:chapter', asyncFunctionN0 )\n\nrest.post( { path: '/make', version: '\u003e=1.0.0' }, asyncFunctionN1 )\n\nrest.post( [ '/act', '/do' ], asyncFunctionN2 )\n\nrest.post( [ { path: '/shake', version: '\u003e=2.0.0' }, { path: '/twist', version: '\u003e=2.1.1' } ], asyncFunctionN3 )\n```\n\n__All service functions must be async!__\n\n[Back to Feature list](#features)\n\n## Assign\n\n#### direct binding\nYou can assign your rest modules by specifying the needed _http_ request functions: __head, get, post, put, delete__.\n\nExample:\n```javascript\nasync function service( request, content ){\n\tconsole.log( 'Received headers:' + JSON.stringify( request.headers ) )\n\tconsole.log( 'Received parameters:' + JSON.stringify( request.parameters ) )\n\tconsole.log( 'Received JSON object:' + JSON.stringify( content ) )\n\treturn 'ok'\n}\nrest.post( [ { path: '/shake', version: '\u003e=2.0.0' }, { path: '/twist', version: '\u003e=2.1.1' } ], service )\n```\n\n#### assign function\nOther way to assign is to use the __assign function__ directly.\n\nExample:\n```javascript\nasync function service( request, content ){\n\t...\n}\n// bind the service funciont to all http request types\nrest.assign( '*', [ { path: '/shake', version: '\u003e=2.0.0' }, { path: '/twist', version: '\u003e=2.1.1' } ], service )\n...\n// bind the service funciont to only the given http request types\nrest.assign( ['head','get','post'], [ { path: '/shake', version: '\u003e=2.0.0' }, { path: '/twist', version: '\u003e=2.1.1' } ], service )\n```\n\n#### Reflective assignement\n\nSee chapter for details: [Reflective publishing](#reflective-publishing)\n\n\n#### parameters\n\nAfter each assign function you might need to pass the followings:\n- a [path description](#path-description)\n- a function to be called.\n\n## Path description\n[connect-rest](https://github.com/imrefazekas/connect-rest) supports many options to be used as path description.\n\nOf course simple paths can be defined as follows:\n```javascript\nrest.get('/user/profile', asyncFunctionN0 )\n```\n\nBut I guess you are interested in more complex solutions. Please, fing them below:\n\n### Regular expression\n```javascript\nrest.get( /^\\/[tT]([a-zA-Z]){4}$/g, asyncFunctionN0 )\n```\n\nThis will match to URIs of _'/api/tAbba'_ but won't to _'/api/t1abcd8'_.\n\n### Named parameters\n```javascript\nrest.get('/books/:title', asyncFunctionN0 )\n```\nor\n```javascript\nrest.get('/books/:title/:chapter', asyncFunctionN0 )\n```\nYou can define parametrized paths for services to accept REST variables from the caller.\nIn this case, whatever string is after the 'books', will be interpret as variable(s) and passed to the service function via the request object.\n\nSo sending a get request to the uri '/api/books/AliceInWonderland/1', will result the following request object:\n```javascript\n{\"headers\": ...,\"parameters\":{\"title\":\"AliceInWonderland\", \"chapter\": \"1\"}}\n```\n\n### Optional parameter\n```javascript\nrest.post('/store/?id', asyncFunctionN )\n```\n\nThis definition allows you to define one optional parameter at the end of the path. It might be called using\n```javascript\n'/store'\n```\nor using\n```javascript\n'/store/108'\n```\npaths. Both HTTP calls will be directed to the same functionN service.\nIn latter case, the '108' will be set as a parameter in the request object with the value of '108'.\n\n### General matcher\n```javascript\nrest.get('/inquire/*book', asyncFunctionM )\n```\nThis definition gives you the possibility to define a general matcher allowing to have been called with anything after the string\n```javascript\n'/inquire'\n```\nso can be called using\n```javascript\n'/inquire/alice/in/wonderland'\n```\nor using\n```javascript\n'/inquire/oz/the/great/wizard'\n```\npaths. This results to have the parameter 'book' with value\n```javascript\n'alice/in/wonderland' or 'oz/the/great/wizard'\n```\nrespectively.\n\nYou can make rather complex mixtures of those options as well:\n```javascript\n'/borrow/:uid/?isbn/:bookTitle'\n```\nOne can call this with uri:\n```javascript\n'borrow/2/AliceInWonderland' or 'borrow/2/HG1232131/AliceInWonderland'\n```\nThe character '*' can be used for both path and version too to make generic bindings:\n```javascript\n{ path: '*', version: '*' }\n```\nBe aware, that this path will be matched to all paths within the defined context.\n\n\n### Range matcher\n```javascript\nrest.get( '/convert/@format', function( request, content ){\n\treturn 'ok'\n}, { format:[ 'euro', 'usd', 'huf' ] } )\n```\nThis 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](https://github.com/imrefazekas/connect-rest) to match the parameter _'format'_ to the array called by the same name.\n\nBy 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.\n\n\n### Special assigns:\nYou can use the all options above at once.\n```javascript\n[ { path: '/rent/:country/?isbn/*bookTitle', version: '\u003c2.0.0' }, { path: '/borrow/:uid/?isbn/?bookTitle', version: '\u003e=2.1.1' } ]\n```\n\nJust define what you really need. :)\n\n\n### Parameter processing\n\nThe logic how [connect-rest](https://github.com/imrefazekas/connect-rest) is managing parameter replacement is the following:\n\nThe 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.\n\n\n## Versioning\nAs for versioning, the syntax is [semantic versioning](http://semver.org), the same you use for [npm](https://npmjs.org)\n```javascript\nrest.get( { path: '/special', version: '1.0.0' }, asyncFunctionN0)\n```\nSo you can use different version specificaiton depending on your need:\n```\nversion: '1.0.0 - 2.9999.9999'\nversion: '2.0.1'\nversion: '2.x'\nversion: '~1'\nversion: '\u003e=1.0.2 \u003c2.1.2'\n```\nOnly the requests defining the right version number will match the defined paths.\n\n[connect-rest](https://github.com/imrefazekas/connect-rest) ignores all unmatching calls which might fail by the badly given path or version.\n\n[Back to Feature list](#features)\n\n\n## Rest functions\n\nA rest function is an async JS function you can define easily.\n\nEvery handler function receives\n- a 'request' object containing \"headers\", \"parameters\", \"files\", \"session\" properties\n- an optional 'content' object which is the object extracted from the http body's payload.\n\n```javascript\nrest.get( { path: '/personal/:uid', version: '1.0.0' }, async function( request, content ){\n\treturn { name: 'John Doe' }\n})\n```\n\nThe result object can be the followings:\n\n- String\n- Buffer\n- Stream\n- Function\n- { result: String | Buffer | Stream | Function, options: object }\n\nBuffers are converted to Strings or JSONs depending on the mime-types. (see the [Customize HTTP response](#customize-http-response) )\n```javascript\nrest.get('/handlers/buffer', async function( request, content ){\n\treturn new Buffer( 'ok', 'utf-8')\n})\n```\nStreams are read to a buffer and returned as strings.\n```javascript\nrest.get('/handlers/stream', async function( request, content ){\n\treturn fs.createReadStream( './test/data/answer.text', { encoding : 'utf-8'} ) )\n})\n```\nFunctions must be async, execution must define the String to be sent back.\n```javascript\nrest.get('/handlers/function', async function( request, content ){\n\treturn async function( ){ return 'ok' }\n})\n```\n\nIf the return object has a 'result' and an 'options' attribute, the result attribute will be considered as return value and options is meant to control HTTP status code or data conversion. See below for details...\n\n[Back to Feature list](#features)\n\n\n## Proxy Rest Services\n\nOne can define proxying REST services easily using [connect-rest](https://github.com/imrefazekas/connect-rest) as follows:\n\n```javascript\nrest.proxy( 'get', '/proxyEmpty', { url: 'http://just-another-site.com:8080/api/empty', method: 'get' } )\n```\n\nThis will create a REST service on path _'[context]/proxyEmpty'_ answering _'GET'_ calls and proxying all calls to a remote point: _'http://just-another-site.com:8080/api/empty'_.\n\nBy default all request parameters will be also sent without any modification. You can prevent this if you set the attribute _'ignoreQuery'_ in the last parameter as follows:\n\n```javascript\nrest.proxy( 'get', '/proxyEmpty', { url: 'http://just-another-site.com:8080/api/empty', ignoreQuery: true } )\n```\n\nConsidering the wide range of REST calls might look like, it could be useful to bypass all headers to the remote site as the following code shows:\n\n```javascript\nrest.proxy( 'get', '/proxyEmpty', { url: 'http://just-another-site.com:8080/api/empty', bypassHeader: true } )\n```\n\nThis will send further all API_KEYS and other header set for a request sent to this service.\n\nOf course the need to use different headers might appear when proxying a request to a remote/foreign point, so you can define your own headers as well:\n\n```javascript\nrest.proxy( 'get', '/proxyEmpty', { url: 'http://just-another-site.com:8080/api/empty', remoteHeaders: { /* key-pairs here */ } } )\n```\n\n[Back to Feature list](#features)\n\n\n## Customize HTTP response\n\nConnect-rest allows you to pass a composed object as return value to control HTTP response like status code.\n\n\n### Status codes\n\n\nAs for status code, all you need to do is this:\n\nError case:\n\n```javascript\nrest.get( '/invalidPath', async function( request, content ){\n\tlet error = new Error('invalid path')\n\terror.statusCode = 404;\n\tthrow error\n});\n```\n\nSpecial case when no error occurred, yet the http request's status has to be set:\n\n```javascript\nrest.get( '/special', async function( request, content ){\n\treturn { result: 'Processing...', options: { statusCode: 202 } }\n})\n```\n\n[Back to Feature list](#features)\n\n### Response headers\n\nTo refine the headers in the response HTML, the way is the same as above: customize the 'options' object of the return value.\n\n```javascript\nrest.get( '/special', function( request, content ){\n\treturn { result: 'Content.', options: { headers: { ETag: \"10c24bc-4ab-457e1c1f\" } } }\n})\n```\n\n### Minify response JSON\n\nYou can make the response JSON object minified by passing a single boolean parameter to the 'options' object:\n\n```javascript\nrest.get( '/special', function( request, content ){\n\t...\n\treturn { result: '{ \"key\"     :    \"value\" }', options: { minify: true } }\n})\n```\n\nThis will send\n```javascript\n{\"key\":\"value\"}\n```\n\nto the client.\n\n\n## Customize answers of REST functions\n\nWhen assigning routes with rest API you can pass an object too. This object looks like this:\n```javascript\n{\n\tcontentType: ''\n\tvalidator: ...\n}\n```\n\nThe contentType defines what the given REST service will retrieve. If not given, 'application/json' will be used.\n\nThe validator is a function, which can be used to determine if the REST function can be called in a given circumstances or should be ignored. This could mean authorization or ip address validation or other security concern.\n\n```javascript\nrest.post( [ { path: '/shake', version: '\u003e=2.0.0' }, { path: '/twist', version: '\u003e=2.1.1' } ], function( request, content ){\n\treturn JSON.stringify(content);\n}, null, { contentType:'application/xml', validator: function(req, res){ return _.contains(req.user.roles, \"superuser\"); } } );\n```\n\n[Back to Feature list](#features)\n\n\n## API_KEY management\n\nThe option passed to the [connect-rest](https://github.com/imrefazekas/connect-rest) might contain an array enumerating accepted api_keys:\n\n```javascript\nvar options = {\n\t'apiKeys': [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ]\n\t...\n}\n```\n\nIf property 'apiKeys' is present, the associated array of strings will be used as the list of api keys demanded regarding every incoming calls.\nSo having such option, a call should look like this:\n\n```javascript\n'/api/books/AliceInWonderland/1?api_key=849b7648-14b8-4154-9ef2-8d1dc4c2b7e9'\n```\n\notherwise error response will be sent with status code 401 claiming: 'API_KEY is required.'.\n\nYou can restrict access on service-level. When you call\n\n```javascript\nrest.get( { path: '/shake', version: '\u003e=2.0.0' }, async function( request, content ){\n\treturn 'OK'\n}, { apiKeys:['1234-1234-1234-1234'] } )\n```\n\nThat will require to use the API_KEY _'1234-1234-1234-1234'_ when call that REST service.\nThis will help you refine your access control on service basis.\n\n\n## Unprotected REST service\nWhen you are using API_KEYs, you still might want to have 'exceptions'.\nFunctions which can be served out of the border os API_KEY restriction.\nYou can turn off that protection for a given service like this:\n\n```javascript\nrest.get( { path: '/special', unprotected: true }, asyncFunctionN0)\n```\n\n## Protector\nProtector 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.\nSo 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](https://github.com/imrefazekas/connect-rest) to allow the rest function's execution to take place or blocked by some security reason.\n\n```javascript\nrest.get( { path: '/special', protector: async function( req, res, pathname, path ){ return 'ok' } }, asyncFunctionN0);\n```\n\nA protector function receives all parameters to able to respond the query the case requires it. For example an A\u0026A protector should manage the necessary measurements and might drop the request.\nRemember: it is designed to be async, trowing exception in the async function will notify the [connect-rest](https://github.com/imrefazekas/connect-rest) to not handle the request.\nYou can have such functions to define session-based dynamic protection or differentiate between widely available rest calls and restricted business-sensitive feature.\n\n[Back to Feature list](#features)\n\n\n## Context\n[connect-rest](https://github.com/imrefazekas/connect-rest) uses context uri prefix by default to create a speparated 'namespace' for the rest functions.\nYou can define it dynamically:\n\n```javascript\nrest.context( '/api' ) // means that every rest calls need to be sent to '/api/X' path.\n```\n\nor through the option object as well when you add the middleware to the connect object:\n\n```javascript\nvar options = {\n\t'context': '/api'\n}\nvar rest = Rest.create( options )\nconnectApp.use( rest.processRequest() )\n```\n\nDefault _context_ is the '/api' string.\n\n## Orchestrating the contexts\n\nThe [connect-rest](https://github.com/imrefazekas/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.\nLet me show you:\n\n```javascript\nrest.get( { path: '/workspace', context: '/pages' }, asyncFunctionN0)\n```\n\nThis REST function can be called by sending a _GET_ request to the address of\n\n```\n/pages/workspace\n```\n\nThis way you can easily manage dynamic templates not being forced to be in the same context as API calls.\n\n__You can orchestrate the contexts of your architecture as it pleases you.__\n\n\n## Discovery services\n[connect-rest](https://github.com/imrefazekas/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.\n\n```javascript\nvar options = {\n\t'discover: { path': 'discover', secure: true }\n}\nvar rest = Rest.create( options )\nconnectApp.use( rest.processRequest() )\n```\n\nThis 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\n\n```\nhttp://localhost:8080/api/discover/3.0.0\n```\n\nwould retrieve all services which can be called using version 3.0.0 (non-versioned and matching versioned services). The returned JSON is the following:\n\n```javascript\n{\n\t\"HEAD\":[\"/peek\"],\n\t\"GET\":[\"discover/:version\",\"/books/:title/:chapter\"],\n\t\"POST\":[\"/store\",{\"path\":\"/make\",\"version\":\"\u003e=1.0.0\"},\"/act\",\"/do\",{\"path\":\"/shake\",\"version\":\"\u003e=2.0.0\"},{\"path\":\"/twist\",\"version\":\"\u003e=2.1.1\"}],\n\t\"PUT\":[],\n\t\"DELETE\":[]\n}\n```\n\nThe option secure tells connect-rest if security should be active for this service.\n\n## Prototype services\nThe 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.\n\n```javascript\nrest.post( [ { path: '/shake', version: '\u003e=2.0.0' }, { path: '/twist', version: '\u003e=2.1.1' } ], asyncFunctionN, { prototypeObject: {'title': 'Alice in Wonderland'} } )\n```\n\nThat parameter debriefs the client what structure the functionN expects to receive.\nTo activate this feature, first you have to add a new attribute to the options object:\n\n```javascript\nvar options = {\n\t'apiKeys': [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],\n\t'proto: { path': 'proto', secure: true },\n\t'logger': 'connect-rest'\n}\n```\n\nThis 'proto' object tells connect-rest that the given path is accepting requests to retrieve prototypes:\n\n```javascript\n'/api/proto/POST/2.3.0/api/twist?api_key=849b7648-14b8-4154-9ef2-8d1dc4c2b7e9'\n```\n\nwill retrieve the object\n\n```javascript\n{'title': 'Alice in Wonderland'}\n```\n\nbecause the service\n\n\ton path '/api/twist' and method 'POST' with version '2.3.0'\n\ncan be called and there is an assigned prototype object to it.\nGiving access method, version and path is mandatory for this feature.\n\nThe option secure tells connect-rest if security should be active for this service.\n\n\n[Back to Feature list](#features)\n\n\n## Remove services\nOne can remove a published service by calling the following function:\n\n```javascript\nrest.unpost( '/shake' )\n```\n\nThat code removes all REST services which would be fired by calling with the URI _'/shake'_.\nThe same path matching logic is used to determine if a given REST function should be removed.\n\nEvery publishing method available in [connect-rest](https://github.com/imrefazekas/connect-rest) has a removing-pair function:\n\n\tunpost, undel, unget ... unassign\n\nThere is a second parameter if you want to specify the version of the services you would like to remove:\n\n```javascript\nrest.unpost( '/shake', 1.0.0 )\n```\n\n... unlinking the service answering to the given URI with the given version.\n\n[Back to Feature list](#features)\n\n\n## Logging\nIn the option object passed to the constructor, there is an optional parameter 'logger', which enables the logging functionality:\n\n```javascript\nvar options = {\n\t'apiKeys': [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],\n\t'discoverPath': 'discover',\n\t'logger': 'connect-rest'\n}\n```\n\nor\n\n```javascript\nvar options = {\n\t'apiKeys': [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],\n\t'discoverPath': 'discover',\n\t'logger': loggerInstance\n}\n```\n\nYou can set:\n- a string, which will be interpret as the name of the logger seen in the logs, or\n- passing a logger instance to be used.\n\nBy default, connect-rest is using [pino](https://github.com/pinojs/pino) as logging library. Here is [why...](https://github.com/pinojs/pino#benchmarks). Keep the compatibility to pino if you are passing own logging solution.\n\nIn the absence of 'logger' property, no logs will be made.\nThe [connect-rest](https://github.com/imrefazekas/connect-rest) will use level 'info' for entry and exit points of services and 'debug' for the milestones of all internal processes.\n\n[Back to Feature list](#features)\n\n\n## Reflective publishing\n[connect-rest](https://github.com/imrefazekas/connect-rest) allows you to have an extremely easy and fast way to publish your services.\n\nYou can define your own services like this in a file (services.js in this example):\n\n```javascript\nfunction health( request ){\n\treturn 'ok'\n}\nfunction record( request, content ){\n\treturn 'saved'\n}\nexports.health = health;\nexports.record = record;\n```\nand publish them this way:\n\n```javascript\nvar services = require('./services')\n...\nrest.publish( services )\n```\n\nThis will discover all functions assigned to the exports having a name which conforms the following regular expression:\n\n```javascript\n/^[a-zA-Z]([a-zA-Z]|\\d|_)*$/g\n```\n\nThe logic is simple. If the function has\n- 1 parameter: it will be a 'get' method\n- 2 parameters: it will be a 'post' method\n\nand the path will be its name. So, by executing one single statement you will automatically have the following services:\n\n\t/health on Get\n\t/record on Post\n\nIf you have 100 services defined, then 100 rest api you will have automatically. Nice.\n\n## Domain support\n[connect-rest](https://github.com/imrefazekas/connect-rest) adds support for domain-based error handling. To the options object you can pass a boolean value requesting the lib to create domain as  [NodeJS docs defines](http://nodejs.org/api/domain.html#domain_domain):\n\n```javascript\nvar options = {\n\tapiKeys: [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],\n\tdiscoverPath: 'discover',\n\tprotoPath: 'proto',\n\tlogger: 'connect-rest',\n\tdomain: true\n}\n```\n\nor you can have a more sophisticated version by passing a complete object as follows:\n\n\n```javascript\nvar options = {\n\tapiKeys: [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],\n\tdiscoverPath: 'discover',\n\tprotoPath: 'proto',\n\tlogger: 'connect-rest',\n\tdomain: {\n\t\tcloseWorker: function(req, res){... },\n\t\tcloseRequest: function(req, res){... }\n\t}\n}\n```\n\nWhere the function __closeWorker__ is an optional function which is called when error occurred and supposed to close the current worker instance if app is running in a node cluster.\n\nThe function __closeRequest__ is an optional function which is called to close the request object on error if you want to perform custom response message. By default [connect-rest](https://github.com/imrefazekas/connect-rest) sets the error code 500 and returns a simple error message 'There was a problem!'.\n\n\n[Back to Feature list](#features)\n\n\n## Answering async rest requests\n\n[connect-rest](https://github.com/imrefazekas/connect-rest) provides a way to serve async rest requests. It might be important - especially between fragmented server-side environment - to call rest services and accept the answer on a specific callback URL specified by the requestor.\n\nThe _client_ has to specify a request parameter _\"callbackURL\"_ possessing the callback URL where the answer has to be sent.\nHaving sent the request, [connect-rest](https://github.com/imrefazekas/connect-rest) will answer it right away with status code _200_ and message _Ok._ and having the result created, it will sent via _HTTP POST_ to the URL given in the HTTP parameters.\n\nThis process is performed behind the scenes, you do not have do anything special about it. If that parameter can be found in the HTTP request, the call will be threaten as async request.\n\n[Back to Feature list](#features)\n\n\n## Dispatchers\n\nIn some cases, you might face with a situation where other 3rd party connect library has to be used and the case might require for path-related logic to be used. [connect-rest](https://github.com/imrefazekas/connect-rest) is designed to be able to use as simple path processing helper library as well.\n\n```javascript\nconnectApp.use( Rest.dispatcher( 'GET', '/dispatcher/:subject', function(req, res, next){\n\tres.end( 'Dispatch call made:' + req.params['subject'] )\n} ) )\n```\nThis simple code makes is pretty straightforward. In case of a _'GET'_ HTTP request coming to the url _'/dispatcher'_, the given function is executed. That function can be any third party connect lib you want to use.\n\n[Back to Feature list](#features)\n\n\n\n## More examples\n\nI have collected a few examples from some implementations submited by users of [connect-rest](https://github.com/imrefazekas/connect-rest).\n\nMight help to have a more complete picture about what you can reach and realize with this library. In case of any wanted scenario, please open a ticket and I will happily comply with it.\n\nExample, how to __restrict rest api calls__ to only those who logged in already, meaning to have some session info\n\n```javascript\nvar protectBySession = function(req, pathname, version){\n\treturn req.session \u0026\u0026 req.session.uid;\n};\nrest.get( { path: '/model/person', unprotected: true, protector: protectBySession, version: '1.0.0' }, async function( request, content ){\n\treturn personModel\n});\n```\n\nExample to how define a __free-to-call rest function__ in a very restricted environment.\n__Dynamic templating__ is a typical scenario, no versioning is needed, nore api_key or session-based protection, must be put on a separate context and result has mime-type of \"text/html\"\n\n```javascript\nvar allower = function(req, pathname, version){\n\treturn true;\n};\nrest.get( { path: '/?page/?id', unprotected: true, protector: allower, context: '/pages' }, async function( request, content ){\n\t// render some page\n\tlet res = await renderer.render( request.parameters.page, request.parameters.id )\n\treturn res\n}, { contentType:'text/html' } )\n```\n\nA fairly complex REST path which is needed in some cases and a custom return status code:\n\n```javascript\nrest.get( '/call/:system/?entity/?version/:subject/*', async function( request, content ){\n\t// Do some business logic\n\treturn { result: 'Done.', options: {statusCode:201} }\n}, { contentType:'application/json' } )\n```\n\nIn this case you call this path by the following uris:\n\n\t/call/library/books/AliceInWonderland\n\t/call/library/books/2.0/AliceInWonderland\n\t/call/library/AliceInWonderland\n\t/call/library/AliceInWonderland/firstedition/chapter1\n\nNot a typical or strictly REST-conform scenario, but you might end up with the need of complex URIs.\n\n__Tip:__ To manage all calls not handled by connect-rest could be also important. The following code demonstrates how to define a small middleware, which is executed when no REST function is matched.\n\n```javascript\nvar rest = Rest.create( options )\napp.use( rest.processRequest() )\napp.use( function(req, res, next){\n\tif(req.session)\n\t\treq.session.destroy()\n\t// render error page by some renderer...\n\trenderer.render( 'error', {}, function(err, html){\n\t\tres.writeHead( 500, { 'Content-Type' : 'text/html' } )\n\t\tres.end( html );\n\t} )\n} )\n```\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2014 Imre Fazekas\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n## Bugs\n\nSee \u003chttps://github.com/imrefazekas/connect-rest/issues\u003e.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimrefazekas%2Fconnect-rest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fimrefazekas%2Fconnect-rest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimrefazekas%2Fconnect-rest/lists"}