Edits history of script submission #17521 for ' Set env var value (netlify)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Netlify = {
      token: string;
    };
    /**
     * Set env var value
     * Updates or creates a new value for an existing environment variable.
     */
    export async function main(
      auth: Netlify,
      account_id: string,
      key: string,
      site_id: string | undefined,
      body: {
        context?:
          | "all"
          | "dev"
          | "branch-deploy"
          | "deploy-preview"
          | "production"
          | "branch";
        context_parameter?: string;
        value?: string;
      },
    ) {
      const url = new URL(
        `https://api.netlify.com/api/v1/accounts/${account_id}/env/${key}`,
      );
      for (const [k, v] of [["site_id", site_id]]) {
        if (v !== undefined && v !== "" && k !== undefined) {
          url.searchParams.append(k, v);
        }
      }
      const response = await fetch(url, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + auth.token,
        },
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        const text = await response.text();
        throw new Error(`${response.status} ${text}`);
      }
      return await response.json();
    }
    

    Submitted by hugo697 235 days ago