Skip to content

Commit

Permalink
Merge pull request #1 from XuluWarrior/strict-mode
Browse files Browse the repository at this point in the history
Strict mode - Throw error if response isn't 2xx
  • Loading branch information
XuluWarrior authored Jan 3, 2024
2 parents f8968ef + b8538bd commit 259e327
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
9 changes: 7 additions & 2 deletions lib/phin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const centra = require('centra')
* @property {Object} [core={}] - Custom core HTTP options
* @property {string} [parse=none] - Response parsing. Errors will be given if the response can't be parsed. 'none' returns body as a `Buffer`, 'json' attempts to parse the body as JSON, and 'string' attempts to parse the body as a string
* @property {boolean} [followRedirects=false] - Enable HTTP redirect following
* @property {boolean} [strict=false] - Throw an error if response is not 2xx
* @property {boolean} [stream=false] - Enable streaming of response. (Removes body property)
* @property {boolean} [compression=false] - Enable compression for request
* @property {?number} [timeout=null] - Request timeout in milliseconds
Expand Down Expand Up @@ -63,6 +64,10 @@ const phin = async (opts) => {
return await phin(opts)
}

if (opts.strict && (res.statusCode < 200 || res.statusCode >= 300)) {
const details = res.body ? ` - ${res.body}` : '';
throw new Error(`${res.statusCode} ${res.coreRes.statusMessage}${details}`)
}
if (opts.stream) {
res.stream = res

Expand All @@ -74,7 +79,7 @@ const phin = async (opts) => {
if (opts.parse) {
if (opts.parse === 'json') {
res.coreRes.body = await res.json()

return res.coreRes
}
else if (opts.parse === 'string') {
Expand All @@ -83,7 +88,7 @@ const phin = async (opts) => {
return res.coreRes
}
}

return res.coreRes
}
}
Expand Down
3 changes: 2 additions & 1 deletion types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface IOptionsBase {
headers?: object
core?: http.ClientRequestArgs
followRedirects?: boolean
strict?: boolean
stream?: boolean
compression?: boolean
timeout?: number
Expand Down Expand Up @@ -43,7 +44,7 @@ declare namespace phin {
export type IWithData<T extends IOptionsBase> = T & {
data: string | Buffer | object;
}

export type IWithForm<T extends IOptionsBase> = T & {
form: {
[index: string]: string
Expand Down

0 comments on commit 259e327

Please sign in to comment.