@richardpickett/api-lib
v1.1.6
Published
A library of notion wrapper classes
Downloads
257
Readme
api lib
Add to your packages.json:
npm i @richardpickett/api-lib
Usage
Extend to make your own api class:
import { Api } from "@richardpickett/api-lib";
class MyApi extends Api {
constructor() {
super({ baseUrl: "https://myApi.com/vi" });
}
async mySpecificApiCall(body) {
return this._fetch({ path: "/my/api/call/path", body });
}
}
const myApi = new MyAPI();
export default myApi;
Quck start: use your API class
import myApi from "./myApi.js";
myApi.mySpecificApiCall({ var: "val" }).then((jsonResult) => {
console.log(JSON.stringify(jsonResult, null, 2));
});
The constructor
constructor({ baseUrl = "", headers = { "Content-Type": "application/json" } })
Override baseUrl
with your api's base Url, and override the headers
as needed. The headers set here are used in all subsequent calls unless the header is deleted with deleteHeader(name)
.
Calling your Api
_fetch({ path = "/", body = false, method = "POST", headers = this.headers, redirect = "follow" })
Typically you will override the path
and body
, overriding the method
, headers
, and redirect
as needed.
path
: appended to the baseUrl
body
: JSON encoded data for POST
(build your own URI parameters and append to path
if using GET
with variables)
method
: all common HTTP methods are supported
redirect
: passed through to node's fetch()
Using specific headers
The headers for every call can be set in the super()
constructor call, like this:
import Api from "@richardpickett/api-lib";
class MyApi extends Api {
constructor() {
super( { baseUrl: "https://myApi.com/vi", headers: { "HeaderName": "HeaderValue" } } )
}
...
You can set specific headers (Auth tokens, etc) via the constructor, or for specific calls when you call _fetch()
. Please note, if you supply headers to the _fetch()
call, it will not use the headers set in the constructor or via setHeader()
The default header set in the constructor is: { "Content-Type": "application/json" }
Setting headers for every call after constructor
Use the following to set/unset the default headers for every call:
setHeader(name, value);
deleteHeader(name);
Using a cookie jar
If your api sets cookies and you need to use them on subsequent calls, use _cookieFetch()
instead of _fetch()
, all the same parameters apply, with the addition that each call will use a cookie jar for each call.