|
1 | 1 | import { Curl, Easy } from 'node-libcurl'; |
2 | | -import { HttpVerb, Options, Response, GetBody } from './types'; |
| 2 | +import { HttpVerb, Options, Response, GetBody, GetJSON } from './types'; |
3 | 3 | import { |
4 | | - checkGetBodyStatus, |
| 4 | + checkValidStatusCode, |
5 | 5 | checkValidCurlCode, |
6 | 6 | handleQs, |
7 | 7 | parseReturnedHeaders, |
@@ -165,14 +165,39 @@ const request = (method: HttpVerb, url: string, options: Options = {}): Response |
165 | 165 | * @returns {Buffer | string} buffer body by default, string body with encoding |
166 | 166 | */ |
167 | 167 | const getBody: GetBody = (encoding?) => { |
168 | | - checkGetBodyStatus(statusCode, body); |
| 168 | + checkValidStatusCode(statusCode, body); |
169 | 169 | return typeof encoding === 'string' ? body.toString(encoding) as any : body; |
170 | 170 | }; |
171 | 171 |
|
| 172 | + /** |
| 173 | + * Get the JSON-parsed body of a response. |
| 174 | + * |
| 175 | + * @throws {Error} if the body is nto a valid JSON |
| 176 | + * @returns {any} parsed JSON body |
| 177 | + */ |
| 178 | + const getJSON: GetJSON = (encoding?) => { |
| 179 | + try { |
| 180 | + return JSON.parse(body.toString(encoding)); |
| 181 | + } catch (err) { |
| 182 | + throw new Error(` |
| 183 | +The server body response for |
| 184 | + - ${method} |
| 185 | + - ${url} |
| 186 | +cannot be parsed as JSON. |
| 187 | +
|
| 188 | +Body: |
| 189 | + ${body.toString(encoding)} |
| 190 | +
|
| 191 | +JSON-Parsing Error Message: |
| 192 | + ${err instanceof Error ? err.message : String(err)} |
| 193 | + `); |
| 194 | + } |
| 195 | + }; |
| 196 | + |
172 | 197 | url = curl.getInfo('EFFECTIVE_URL').data as string; |
173 | 198 |
|
174 | 199 | curl.close(); |
175 | | - return { statusCode, headers, body, getBody, url }; |
| 200 | + return { statusCode, headers, url, body, getBody, getJSON }; |
176 | 201 | }; |
177 | 202 |
|
178 | 203 | export default request; |
0 commit comments