Skip to content

Commit

Permalink
feat: add promise mode
Browse files Browse the repository at this point in the history
you can now do `let [res, body] = await miniget.promise(url)`
  • Loading branch information
fent committed Feb 24, 2020
1 parent fa87d89 commit 9589701
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ Makes a GET request. `options` can have any properties from the [`http.request()
```
Given encodings will be added to the `Accept-Encoding` header, and the response will be decoded if the server responds with encoded content.

If `callback` is given, will concatenate the response, and call `callback` with a possible error, the response, and the response body.
If `callback` is given, will concatenate the response, and call `callback` with a possible error, the response, and the response body. If you'd like a concatenated response, but want to use `await` instead, you can call `miniget.promise()`.

```js
let [res, body] = await miniget.promise('http://yourwebsite.com');
```

Miniget returns a readable stream if `callback` is not given, errors will then be emitted on the stream. Returned stream also contains an `.abort()` method, and can emit the following events.

Expand Down
13 changes: 13 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,17 @@ function Miniget(url: string, options?: Miniget.Options | Callback, callback?: C
return callback ? null : stream;
}

// istanbul ignore next
// https://github.com/istanbuljs/nyc/issues/1209
namespace Miniget {
export const promise = (url: string, options?: Options): Promise<[IncomingMessage, string]> => {
return new Promise((resolve, reject) => {
Miniget(url, options, (err, res, body) => {
if (err) return reject(err);
resolve([res, body]);
});
});
};
}

export = Miniget;
25 changes: 25 additions & 0 deletions test/request-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,31 @@ describe('Make a request', () => {
});
});

describe('with a promise', () => {
it('Gives contents of page', async () => {
const scope = nock('http://webby.com')
.get('/pathos')
.replyWithFile(200, __filename);
let [res, body] = await miniget.promise('http://webby.com/pathos');
scope.done();
assert.equal(res.statusCode, 200);
assert.ok(body.length > 100);
});

describe('that errors', () => {
it('error is caught', async () => {
const scope = nock('http://something.com')
.get('/one/two/three')
.replyWithError('NONONO');
await assert.rejects(
miniget.promise('http://something.com/one/two/three', { maxRetries: 0 }),
null, 'NONONO'
);
scope.done();
});
});
});

describe('that errors', () => {
it('Emits error event', (done) => {
const scope = nock('https://mysite.com')
Expand Down

0 comments on commit 9589701

Please sign in to comment.