Skip to content

Commit

Permalink
Support returning body without wrapping it in a function (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevva authored and lukechilds committed Feb 16, 2018
1 parent 03dcb00 commit 5788767
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -39,6 +39,7 @@ createTestServer().then(server => {
});

// You can return a body directly too
server.get('/foo', 'foo');
server.get('/foo', () => 'foo');

// server.url + '/foo' and server.sslUrl + '/foo' will respond with 'bar'
Expand Down
4 changes: 3 additions & 1 deletion src/index.js
Expand Up @@ -13,7 +13,9 @@ const createTestServer = opts => createCert(opts && opts.certificate)
const server = http.createServer(app);
const sslServer = https.createServer(keys, app);
const send = fn => (req, res) => {
new Promise(resolve => resolve(fn(req, res))).then(val => {
const cb = typeof fn === 'function' ? fn(req, res) : fn;

new Promise(resolve => resolve(cb)).then(val => {
if (val) {
res.send(val);
}
Expand Down
15 changes: 15 additions & 0 deletions test/create-test-server.js
Expand Up @@ -106,3 +106,18 @@ test('support returning body directly', async t => {
t.deepEqual(bodyJson, { foo: 'bar' });
t.deepEqual(bodyAsync, 'bar');
});

test('support returning body directly without wrapping in function', async t => {
const server = await createTestServer();

server.get('/foo', 'bar');
server.get('/bar', ({ foo: 'bar' }));
server.get('/async', Promise.resolve('bar'));

const bodyString = (await got(server.url + '/foo')).body;
const bodyJson = (await got(server.url + '/bar', { json: true })).body;
const bodyAsync = (await got(server.url + '/async')).body;
t.deepEqual(bodyString, 'bar');
t.deepEqual(bodyJson, { foo: 'bar' });
t.deepEqual(bodyAsync, 'bar');
});

0 comments on commit 5788767

Please sign in to comment.