async post()

in slingpost/index.js [227:270]


  async post(path, params) {
    this.log.debug(`Posting to: ${path}`);

    this.log.silly(`Sending parameters: ${JSON.stringify(params)}`);
    const formData = new FormData();
    Object.keys(params).forEach((key) => {
      if (Array.isArray(params[key])) {
        for (const val of params[key]) {
          formData.append(key, val);
        }
      } else {
        formData.append(key, params[key]);
      }
    });
    const response = await fetch(`${this.config.url}${path}`, {
      method: "POST",
      headers: {
        Authorization: `Basic ${Buffer.from(
          this.config.username + ":" + this.config.password
        ).toString("base64")}`,
        Accept: "application/json",
      },
      body: formData,
    });
    if (!response.ok) {
      const body = await response.text();
      this.log.silly(`Retrieved error response: ${body}`);
      throw new Error(
        `Failed with invalid status: ${response.status} - ${response.statusText}`
      );
    } else {
      this.log.debug(
        `Post successful: ${response.status} - ${response.statusText}`
      );
      const body = await response.text();
      this.log.silly(`Retrieved response: ${body}`);
      return {
        ok: response.ok,
        status: response.status,
        statusText: response.statusText,
        body,
      };
    }
  }