macotron.http
Make HTTP requests from a plugin. Every call returns a promise that resolves with the status, the body as text, and the response headers.
const res = await macotron.http.get("https://wttr.in/?format=%t", {
headers: { "User-Agent": "curl/8.0" },
timeout: 8000,
});
if (res.status === 200) macotron.menubar.setTitle(res.body.trim());
Requests
get(url: string, opts?: HTTPOptions): Promise<HTTPResponse>
Sends a GET request.
post(url: string, body: any, opts?: HTTPOptions): Promise<HTTPResponse>
Sends a POST request. An object or array body is sent as JSON. Anything else is sent as its string, in UTF-8. The Content-Type header defaults to application/json; set it in headers for a form or plain text.
put(url: string, body: any, opts?: HTTPOptions): Promise<HTTPResponse>
Sends a PUT request. The body works the same as for post().
delete(url: string, opts?: HTTPOptions): Promise<HTTPResponse>
Sends a DELETE request.
const res = await macotron.http.post(
"https://api.example.com/items",
{ name: "Milk" },
{ headers: { Authorization: "Bearer " + macotron.keychain.get("example-token") } }
);
Options
HTTPOptions: { headers?, timeout? }
timeout is in milliseconds. The default is 30000.
headers sets request headers, with any names. A Cookie header replaces the cookies macOS would send for that site.
Requests share the system cookie store. When you set Cookie yourself, that request leaves the shared store out, so your value is the one sent.
Responses
HTTPResponse: { status, body, headers }
status is the HTTP status code. body is the response decoded as UTF-8 text, or "" when it is not valid UTF-8. headers holds the response headers as strings.
The promise never rejects. A 404 or 500 resolves like any other response. A request that never completes, because of a bad URL, a timeout, or no network, resolves with status: 0 and the reason in body, such as "Invalid URL" or "Request timed out". One check of status covers both cases.
const res = await macotron.http.get(feed);
if (res.status === 200) {
const data = JSON.parse(res.body);
// …
} else {
console.log("Feed failed:", res.status || res.body);
}
See also
- macotron.ai for model APIs, with streaming.
- macotron.keychain to store tokens.
- The
weather.jsplugin, which polls a weather service withget().