candyget v0.5.6
Features
- Super small
- No dependency
- HTTP request by one line
- Promise based
- Infer HTTP method automatically
- Stringify/parse JSON automatically
- Decompress gzip/brotli/deflate automatically
- Handle redirects
- User selectable response type
- Full TypeScript Support
Usage
const candyget = require("candyget");
// simply get
const { statusCode, body } = await candyget("https://example.com", "string");
// or simply: candyget.string("https://example.com");
// simply post
const { body: json } = await candyget("https://your.site/", "json", null, {
foo: "bar",
});
// response can be streamed
const { body: stream } = await candyget("https://foo.bar/bin", "stream");
stream.pipe(require("fs").createWriteStream("foo.bin"));
// Customize default options
candyget.defaultOptions.headers["Custom-Header"] = "foo";API
candyget(url, returnType, options?, body?)
candyget(method, url, returnType, options?, body?)
Make HTTP(S) request to the specified URL and return the result.
When no method provided, candyget will automatically infer the method type; if body is present, it will infer as POST, otherwise GET.
urlcan be astringor aURLobject.returnTypecan be either of the followings:"string"-bodyin the returned object will be astring."buffer"-bodywill be aBuffer."stream"-bodywill be aReadable."json"-bodywill be a parsed object. If failed to parse,bodywill be astring."empty"- Only make a request.bodywill benull. You cannot handle the response (since v0.4.0).
optionsis an object that can have the following properties. All these properties are optional in most cases. Passingnullorundefinedasoptionsequals passing{}. |Option|Default|Description| |------|-------|-----------| |timeout|10000|Number to pass tohttp.request, represents the timeout in milliseconds.| |headers|(See description)|Object that presents HTTP headers. HTTP headers set here anddefaultOptions.headerswill be merged and send in the request. (If same headers are present in both of them, the one inoptions.headerswill be used.) By default,candygetwill sendAccept,Accept-Language,Accept-EncodingandUser-Agentheaders. If you want to change the default, refer to the defaultOptions below. | |agent||http.Agentto passhttp.request. |transformerOptions|{autoDestroy:true}|Optional parameters to pass toPassThrough, which will be used if you set thereturnTypetostream.| |maxRedirects|10|Numberthat represents the redirect limit. If redirected more than the limit, candyget will return the HTTP redirect response as a resolved result.| |body||Astring,Buffer,Streamor a plain object (with nocyclic reference). You can pass the request body instead of the last argument.| |validator||Afunctionto validate if the response body has the expected type. See below for more info.| |fetch|true|Abooleanor anobjectincluding the fetch API implementation used by candyget. If it is set totrueand in Node.js (^16.15.0 with--experimental-fetchor >=17.5.0), candyget will use the nativefetchAPI. This can also be set to your customfetchAPI implementation like below. BothfetchandAbortControllerare required. It is not allowed to pass only one of them.|const fetch = require("your-favorite-fetch-lib"); const AbortController = require("your-favorite-abortController-polyfill"); const result = await candyget(METHOD, URL, RETURN_TYPE, { fetch: { fetch, AbortController, } });Note Not all polyfills are supported and some polyfills will neglect working. For instance,
undiciwithabort-controllerwon't work.bodycan be astring,Buffer,Streamor a plain object (with no cyclic reference). Ifoptions.bodyandbodyare passed at the same time,bodywill be used as a request body.
candyget returns a promise.
If a non-HTTP error (e.g., a network error) occurs, the promise will be rejected.
Warning If you specify
options.validatorandcandygetfails to validate the response body, the promise will be rejected, even if there is no non-HTTP error.
Otherwise the promise will be resolved as an object, which has the following properties.
|Property Name|Description|
|-------------|-----------|
|statusCode|HTTP status code of the response.|
|headers|IncomingHttpHeaders, the response headers.|
|body|The response body, type of which is what you specified.|
|request(deprecated)|If candyget used http/https module, this will be http.ClientRequest. On the other hand if fetch module or fetch-like module, this will be null.|
|response(deprecated)|If candyget used http/https module, this will be http.IncomingMessage. On the other hand if fetch module or fetch-like module, this will be the Response object.|
|url|URL, which is the resolved url.|
candyget.defaultOptions
The default options (excluding the body property), which are used by candyget.
It is possible to change candyget's default options globally by overriding it.
Shorthand functions
By return types
Instead of passing the return type as a parameter, you can use shorthand functions.
candyget(URL, "string");
// equals
candyget.string(URL);
candyget(URL, "json", OPTIONS, BODY);
// equals
candyget.json(URL, OPTIONS, BODY);Please note that you cannot specify a HTTP method when using these shorthand functions. They automatically infer the correct HTTP method.
By HTTP methods
You can use shorthand functions instead of passing the HTTP method as a parameter.
candyget("GET", URL, RETURN_TYPE, OPTIONS, BODY);
// equals
candyget.get(URL, RETURN_TYPE, OPTIONS, BODY);
candyget("HEAD", URL, "empty", OPTIONS);
// equals
candyget.head(URL, OPTIONS);By using these shorthand functions, TypeScript users can benefit in many ways by type checks. (For example, if you use candyget.post, TypeScript will throw an error unless you specify the request body)
For TypeScript users
Response body validation
When you specify json as the return type, the body property in the result will be typed as any. However, if you include a validator property in the options, the response body will be correctly typed.
type resultType = {
data: string,
}
const result = await candyget.get<resultType>("https://your.site/great/content", "json", {
validator(responseBody): responseBody is resultType {
return typeof responseBody.data === "string";
},
});
console.log(result.body);It is beneficial to write your custom validation function, with or without using a schema validator such as ajv or zod, in the validator option. Please note that if you specify a validator and the response body fails validation, the promise will be rejected even if there is no HTTP error.
Note
Due to complex overloads, TypeScript may mark some errors at a different location than the actual incorrect location. In this situation, ensure that your parameters are passed correctly, for example, by avoiding duplicated request bodies or by correctly ordering the parameters. However, if you believe that it could be a bug, feel free to create a new issue.
License
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago