Skip to content

Commit

Permalink
Merge 3c0d9c4 into 84cc3bd
Browse files Browse the repository at this point in the history
  • Loading branch information
toddself committed Nov 16, 2018
2 parents 84cc3bd + 3c0d9c4 commit d219ade
Show file tree
Hide file tree
Showing 15 changed files with 805 additions and 476 deletions.
5 changes: 4 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
language: node_js
node_js:
- node
- "6"
- "7"
- "8"
- "9"
30 changes: 30 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Version 2.0.0
* Removed middleware
* `next` is no longer the third arugments to routes, this has been replaced with `ctx`
* If you need middleware, just provide an array of functions to the router
* Enabled the ability to create an HTTPS server
* Passing in `opts.http.{key, ca, cert}` will now make an HTTPS server
* The built-in `HTTPServer`, `Request` and `Response` objects are no longer modified
* The `ctx` object now contains the keys previously placed into `req` and `res`
* The result of `new TakeFive()` is a TakeFive object. The underlying node server instance may be accessed via `.server` on the resulting object

# Version 1.3.4
* Update deps from greenkeeper

# Version 1.3.3
* Fix a typo preventing `cors` options from being overridden

# Version 1.3.2
* Fix bug where zero-length bodies would attempt to be parsed

# Version 1.3.1
* Fix bug where we sent a pre-generated content-length header that caused issues with `.pipe(res)`

# Version 1.3.0
* Add `Access-Control-Allow-Methods` to CORS options

# Version 1.2.0
* Make sure to always call `res.end`

# Version 1.1.1
* First useable release. Added license & benchmarks
209 changes: 153 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# take-five

[![Greenkeeper badge](https://badges.greenkeeper.io/scriptoLLC/take-five.svg)](https://greenkeeper.io/)
[![Build Status](https://travis-ci.org/scriptoLLC/take-five.svg?branch=master)](https://travis-ci.org/scriptoLLC/take-five) [![NSP Status](https://nodesecurity.io/orgs/scriptollc/projects/24857fc4-2472-446e-ac2d-5a0f5913503d/badge)](https://nodesecurity.io/orgs/scriptollc/projects/24857fc4-2472-446e-ac2d-5a0f5913503d) [![Coverage Status](https://coveralls.io/repos/github/scriptoLLC/take-five/badge.svg?branch=master)](https://coveralls.io/github/scriptoLLC/take-five?branch=master)

A minimal REST server that deals solely with JSON payloads that automatically
Expand All @@ -15,11 +14,11 @@ npm install -S take-five
## Usage

```js
const five = require('take-five')
const server = five()
server.get('/', (req, res) => res.send('Hello, world'))
server.post('/', (req, res) => res.send(req.body))
server.listen(3000)
const Five = require('take-five')
const five = new Five()
five.get('/', async (req, res, ctx) => ctx.send('Hello, world'))
five.post('/', async (req, res, ctx) => ctx.send(req.body))
five.listen(3000)
```

```
Expand All @@ -29,84 +28,182 @@ curl -X POST localhost:3000 -H 'content-type: application/json' -d '{"hello": "w
{"hello": "world"}
```

## API
## Routing and route-handlers
In lieu of pre-set middleware, routes handlers can be arrays of functions that will
be iterated over asynchronously. To simplify handling of these handlers,
it is expected that the handlers will return then-ables. This means any promises
library should work (including the built in one), as well as using the `async` function
keyword.

### `five(opts?:object):object`
Create and return a new HTTP server object.
If you have either closed the response stream, or `reject`ed the then-able returned
from your route handler, the next route will not be called. In the case that you have
`reject`ed the then-able, the error handler will be invoked as well. If you have
closed the response stream, the server assumes you were done processing the request
and will just ignore the remaning functions in the queue.

* `opts.maxPost?:number`: the max size for a payload. Default: 512kb
* `opts.cors?:object`
* `opts.cors.headers?:array(string)`: an array of headers to accept besides the default. Default: `Content-Type`, `Accept`, `X-Requested-With`
* `opts.cors.origin?:string`: What origin(s) are accepted. Deafult: `*`
* `opts.cors.credentials?:boolean`: Allow or deny credentials. Default: `true`
* `opts.cores.methods?array(string)`: an array of methods to accept besides the default. Default: `PUT`, `POST`, `DELETE`, `GET`, `OPTIONS`
By default, `get`, `post`, `put`, `delete`, `options` and `patch` will be available
for routing, but this can be changed by providing an array of methods on the options
hash when instatiating a new TakeFive prototype.

### `Five#use(middleware:function)`
Add a new middleware to the stack. Middleware will be processed in the order in
which they are added, which means they will be run after the built-in middleware.
### Examples

* `middleware(request:object, response:object, next:function):function` -You must either call `next` or send data to the client when you are finshed.
#### Using async/await
```js
five.handleError = (err, req, res, ctx) => {
ctx.err(err.statusCode, err.message)
}

five.get('/:secretdata', [
async (req, res, ctx) => {
try {
const session = await isAuthorized(req.headers.Authorization)
ctx.session = session
} catch (err) {
err.statusCode = 401
throw err
}
},
async (res, res, ctx) => {
try {
const data = await getResource(ctx.params.secretdata, ctx.session)
ctx.send(data)
} catch (err) {
err.statusCode = 500
reject(err)
}
}
])
```

#### Using a "then"-able
```js
five.get('/:secretdata', [
(req, res, ctx) => {
return new Promise((resolve, reject) => {
isAuthorized(req.headers.Authorization, (err, session) => {
if (err) {
ctx.err(401, 'Not Authorized')
return reject(new Error('Not authorized'))
}
ctx.session = session
resolve()
})
})
},
(res, res, ctx) => {
return new Promise((resolve, reject) => {
getResource(ctx.params.secretdata, ctx.session, (err, data) => {
if (err) {
ctx.err(500, 'Server error')
return reject(new Error('server error'))
}
ctx.send(data)
resolve()
})
})
}
])
```

Since the middleware signature is the same express/restify, you *might* be able to use existing middleware with take-five, but ymmv.
## API

### `Five#router(namespace:string):object`
Namespace routes. All routes defined off this router will be prefixed with the supplied
namespace. The methods have the same signature as the router provided.
### `Five(opts?:object):object`
Create and return a new HTTP server object.

### `Five#get(route:string, handler:(function|array(function)))`
### `Five#post(route:string, handler:(function|array(function)))`
### `Five#put(route:string, handler:(function|array(function)))`
### `Five#delete(route:string, handler:(function|array(function)))`
* `opts.maxPost?:number`: the max size for a payload. Default: 512kb
* `opts.allowHeaders?:array(string)`: an array of headers to accept besides the default. Default: `Content-Type`, `Accept`, `X-Requested-With`
* `opts.allowOrigin?:string`: What origin(s) are accepted. Deafult: `*`
* `opts.allowCredentials?:boolean`: Allow or deny credentials. Default: `true`
* `opts.allowContentTypes?:string|string[]`: What content types are allowed to be used when sending data to the server. Default: `['application/json']`. Note: This is additive, so `application/json` will ALWAYS be allowed.
* `opts.allowMethods?array(string)`: an array of methods to accept besides the default. Default: `PUT`, `POST`, `DELETE`, `GET`, `OPTIONS`, `PATCH`
* `opts.methods?array(string)`: An array of methods to create route handlers for. Default: `PUT`, `POST`, `DELETE`, `GET`, `OPTIONS`, `PATCH`
* `opts.http?object`: options for `http(s).createServer`. If you supply `key`,
`cert` and `ca` as options, it will assume you are trying to create an https server`

`Access-Control-Allow-Headers` and `Access-Control-Allow-Methods` can also be changed during runtime
by setting `allowHeaders` and `allowMethods` respectively.

#### `Five#get(route:string, handler:(function|array(function)), routeOpts?:object)`
#### `Five#post(route:string, handler:(function|array(function)), routeOpts?:object)`
#### `Five#put(route:string, handler:(function|array(function)), routeOpts?:object)`
#### `Five#patch(route:string, handler:(function|array(function)), routeOpts?:object)`
#### `Five#delete(route:string, handler:(function|array(function)), routeOpts?:object)`
#### `Five#options(route:string, handler:(function|array(function)), routeOpts?:object)`
Add a new route to the server. Routes may be added after the server has been
started. You can supply either a single function or an array of functions to call.
The array will be traversed in the order it is supplied

* `route:string` A [wayfarer](https://github.com/yoshuawuyts/wayfarer) route definition.
* `handler(request:object, response:object, next:function):function`: The handler for this route.
* `handler(request:object, response:object, ctx:object):function`: The handler for this route.
* `routeOpts?:object` - overrides for this specific chain of handlers
* `maxPost:number` - set the maximum size of a payload for this set of handlers
* `allowedContentTypes:string|string[]` - add new allowable content-types for this set of handlers

#### `ctx:object`
* `query?:object`: query parameters from the URL (if any)
* `params?:object`: Named parameters from the route definition as provided by wayfarer
* `body?:object`: The parsed JSON body available on POST requests
* `send(statusCode?:number, body?:(string|object)):function`: Send a response.
* `err(statusCode?:number, message?:string):function`: Send an error. If no status code is provided it will default to a 500 error. If no message is provided, it will use the default message for that status code. The message will be wrapped in a JSON object under the key `message`
* `next():function`: Go to the next handler

Since this is an augmented instance of [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
all methods and properties are available on this as well.
The `ctx` object can also be extended to contain user defined objects, through
setting `this.ctx` to an object. The object will be copied over using `Object.assign`.

### `request:object`
The [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
object extended with:
The keys from above will overwrite any keys you provide named the same.

* `params?:object`: query parameters from the URL (if any)
* `urlParams?:object`: Named parameters from the route definition as provided by wayfarer
* `body?:object`: The parsed JSON body available on POST requests
#### `Five#handleError(err:Error, req:Request, res:Response, ctx:Context)`
This function is invoked when either an error object is passed to the `ctx.next`
method, or the `then`-able function's `reject` handler is invoked.

### `response:object`
The [`http.ServerResponse`](https://nodejs.org/api/http.html#http_class_http_serverresponse)
object augmented with two additional methods. The defaults for sending messages are
`content-type: application/json` and `statusCode: 200`. The header may be overridden by
calling `res.header`. The statusCode can be provided when calling the `send` method.
This is a no-op by default, allowing you to customize it's behavior.

* `send(statusCode?:number, body?:(string|object)):function`: Send a response.
* `err(statusCode?:number, message?:string):function`: Send an error. If no status code is provided it will default to a 500 error. If no message is provided, it will use the default message for that status code. The message will be wrapped in a JSON object under the key `message`
#### `Five#listen(port:number, handle?:function)`
Start listening for requests and call the optional callback when you've started
listening

#### `Five.addParser(type:string, parser:functon):void`
Add a new content parser to the parsers list. By default there is only a single
parser (`application/json`: JSON.parser). This can be overridden with a custom
JSON parser if you'd like.

#### `Five#close()`
Shutdown the underlying server

### Getters/Setters

#### `Five.server`
The underlying http(s) server from node can be accessed directly. This is non-writeable

### `next:function`
If you are done processing the request, but you want a later handler to be able to modify the response, call next. This will invoke the next handler in the stack. If there are no more handlers left, it will call `res.end()` and send the response as is. If you want to immediately send the response, you can call `res.end`, `res.send` or `res.err` directly.
#### `Five.maxPost`
Globally control the maximum payload size after creation

#### `Five.allowContentTypes`
Add new allowable content types for clients to send data with. You can use either
an array of strings or a string

#### `Five.allowHeaders`
Set a new allowable header or headers for CORS requests. You can use either an
array of strings or a string.

#### `Five.allowMethods`
Set a new allowable method for CORS requests.

#### `Five.ctx`
Add new keys to the ctx objects

## Do we need another REST server?
Probably not, but [`restify`](http://restify.com), [`hapi`](http://hapijs.com) and [`express`](http://expressjs.com) are all over-kill on the types of services I'm building for the most part.
* Setting up CORS is difficult or laborious: most REST services need to support CORS, this should be enabled by default (and easily configurable)
* It has no need to accept anything other than `application/json` payloads, and doesn't need the cruft associated with other payload types.
* By default it woill respond with `application/json` as well, but allow it be override-able if needed
* It has no need to accept anything other than `application/json` payloads, but you can easily extend it to
* By default it will respond with `application/json` as well, but allow it be override-able if needed
* Should be trivial to reject large payloads to prevent DOS attacks
* Each route should have the ability to have multiple placeholders, regardless of the payload type
* It shouldn't mutate the built-in request and response objects
* It should be as fast as possible

I found that the other three projects aim to support way more than this, which means supporting these features involves jumping through hoops or installing a ton of
various other packages.

There are some scripts used for the (extremely reductive) benchmarking in `/benchmark`. Using my Core-i7, I get the following data using `wrk -t12 -c400 -d30s http://localhost:3000/test`. You might see different results. As with all benchmarks, these are likely indicative of nothing!

```
take-five: Requests/sec: 20296.63
express: Requests/sec: 10974.18
restify: Requests/sec: 9201.09
```

## License
Copyright © 2016 Scripto LLC, Todd Kennedy. Reuse permitted under the Apache-2.0 license
Copyright © 2018 Scripto LLC, Todd Kennedy. Reuse permitted under the Apache-2.0 license
6 changes: 0 additions & 6 deletions benchmark/express.js

This file was deleted.

15 changes: 0 additions & 15 deletions benchmark/package.json

This file was deleted.

6 changes: 0 additions & 6 deletions benchmark/restify.js

This file was deleted.

6 changes: 0 additions & 6 deletions benchmark/take-five.js

This file was deleted.

29 changes: 0 additions & 29 deletions lib/cors.js

This file was deleted.

31 changes: 0 additions & 31 deletions lib/handle-request.js

This file was deleted.

Loading

0 comments on commit d219ade

Please sign in to comment.