Edits history of script submission #11964 for ' Create a new organization membership (clerk)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Clerk = {
      apiKey: string;
    };
    /**
     * Create a new organization membership
     * Adds a user as a member to the given organization.
    Only users in the same instance as the organization can be added as members.
    
    This organization will be the user's [active organization] (https://clerk.com/docs/organizations/overview#active-organization)
    the next time they create a session, presuming they don't explicitly set a
    different organization as active before then.
     */
    export async function main(
      auth: Clerk,
      organization_id: string,
      body: { user_id: string; role: string },
    ) {
      const url = new URL(
        `https://api.clerk.com/v1/organizations/${organization_id}/memberships`,
      );
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + auth.apiKey,
        },
        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 428 days ago