Skip to content

Commit

Permalink
feat: Add app.handler property
Browse files Browse the repository at this point in the history
  • Loading branch information
nwoltman committed Jun 27, 2019
1 parent a4d1655 commit fa47137
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 3 deletions.
27 changes: 27 additions & 0 deletions docs/App.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const app = medley();
**Properties:**

+ [`.basePath`](#base-path)
+ [`.handler`](#handler)
+ [`.server`](#server)

**Methods:**
Expand Down Expand Up @@ -48,6 +49,32 @@ const subSubApp = subApp.createSubApp('/user');
console.log(subSubApp.basePath); // '/v1/user'
```

<a id="handler"></a>
### `app.handler`

The function passed to `http.createServer()` that handles requests.

This property is `null` until the app has finished [loading](#load).

Helpful when testing with tools like [`supertest`](https://github.com/visionmedia/supertest).

```js
const request = require('supertest');

describe('GET /', function() {
it('responds successfully', async function() {
const app = buildAppSomehow();

await app.load();

return request(app.handler)
.get('/')
.expect('content-type', /html/)
.expect(200);
});
});
```

<a id="server"></a>
### `app.server`

Expand Down
10 changes: 7 additions & 3 deletions medley.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,16 @@ function medley(options) {
server = http.createServer(requestHandler)
}

var loadCallbackQueue = null
var loaded = false

const app = {
server,

get handler() {
return loaded ? requestHandler : null
},

createSubApp,

// Decorator methods
Expand Down Expand Up @@ -128,9 +135,6 @@ function medley(options) {

var registeringAutoHandlers = false

var loadCallbackQueue = null
var loaded = false

function throwIfAppIsLoaded(msg) {
if (loaded) {
throw new Error(msg)
Expand Down
24 changes: 24 additions & 0 deletions test/app-handler.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

const t = require('tap')
const medley = require('..')

t.plan(5)

const app = medley()
const mockReq = {method: 'GET', url: '/'}
const mockRes = {}

app.addHook('onRequest', (req, res) => {
t.equal(req.stream, mockReq)
t.equal(res.stream, mockRes)
})

t.equal(app.handler, null, 'app.handler is null before app is loaded')

app.load((err) => {
t.error(err)
t.type(app.handler, 'function')

app.handler(mockReq, mockRes)
})

0 comments on commit fa47137

Please sign in to comment.