Skip to content

Commit c8ccb46

Browse files
Merge pull request #122 from bitgopatmcl/beta
fix(superagent): do not throw on non-2xx status
2 parents 48f0d5f + de5132c commit c8ccb46

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

packages/superagent-wrapper/src/request.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,10 @@ const patchRequest = <Req extends SuperAgentRequest, Route extends h.HttpRoute>(
139139
return res as ExpectedDecodedResponse<Route, StatusCode>;
140140
}
141141
});
142+
143+
// Stop superagent from throwing on non-2xx status codes
144+
patchedReq.ok(() => true);
145+
142146
return patchedReq;
143147
};
144148

packages/superagent-wrapper/test/request.test.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import express from 'express';
55
import * as E from 'fp-ts/Either';
66
import * as t from 'io-ts';
77
import { NumberFromString } from 'io-ts-types';
8+
import superagent from 'superagent';
89
import supertest from 'supertest';
10+
import { URL } from 'url';
911

10-
import { supertestRequestFactory } from '../src/request';
12+
import { superagentRequestFactory, supertestRequestFactory } from '../src/request';
1113
import { buildApiClient } from '../src/routes';
1214

1315
const PostTestRoute = h.httpRoute({
@@ -184,4 +186,32 @@ describe('request', () => {
184186
assert.isTrue(result);
185187
});
186188
});
189+
190+
describe('superagent', async () => {
191+
it('does not throw on non-2xx status codes', async () => {
192+
// Figure out what host/port supertest set up (the response is just thrown away on purpose)
193+
const superTestReq = apiClient['api.v1.test'].post({
194+
id: 1337,
195+
foo: 'test',
196+
bar: 42,
197+
});
198+
199+
// Construct an api client that uses superagent, with the base url extracted from the supertest
200+
// request above.
201+
const url = new URL(superTestReq.url);
202+
url.pathname = '/';
203+
const superagentClient = buildApiClient(
204+
superagentRequestFactory(superagent, url.toString()),
205+
TestRoutes,
206+
);
207+
208+
const req = await superagentClient['api.v1.test']
209+
.post({ id: 1337, foo: 'test', bar: 42 })
210+
.set('x-send-unexpected-status-code', 'true')
211+
.decode();
212+
213+
assert.equal(req.status, 'decodeError');
214+
assert.equal(req.original.status, 400);
215+
});
216+
});
187217
});

0 commit comments

Comments
 (0)