Skip to content

Latest commit

 

History

History
70 lines (50 loc) · 1.54 KB

README.md

File metadata and controls

70 lines (50 loc) · 1.54 KB

Scriptable Utils

Utility libraries for Scriptable.

Requests

Basic usage

const Requests = importModule("Requests");

const requests = new Requests("https://api.github.com");

// get json
await requests.get("/user/TimonPeng", { loadMethod: "loadJSON" });

// get image
await requests.get("/captcha", { loadMethod: "loadImage" });

// ...

Cookies keeping

You need to use cache.js or something to save the cookies to somewhere.

const Requests = importModule("Requests");
const Cache = importModule("Cache");

const cookiesCache = new Cache("Cookies");

class RequestsWithCookies extends Requests {
  toCookiesString(cookies) {
    const array = [];

    for (const [key, value] of Object.entries(cookies)) {
      array.push(`${key}=${value}`);
    }

    return array.join("; ");
  }

  async beforeRequest(request) {
    const host = request.url.split("/")[2];
    const cookies = (await cookiesCache.read(host)) || {};

    request.headers = {
      ...{ Cookie: this.toCookiesString(cookies) },
      ...request.headers,
    };
  }

  async afterRequest(request, response) {
    // console.log(
    //   `${request.url} -> data: ${JSON.stringify(
    //     response
    //   )} response: ${JSON.stringify(request.response)}`
    // );

    const cookies = {};

    for (const cookie of request.response.cookies || []) {
      const { domain, name, value } = cookie;
      cookies[name] = value;
      cookiesCache.write(domain, cookies);
    }
  }
}