Edits history of script submission #22327 for ' Upsert Record (salesforce)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_sobject = string
    
    // Dropdown of the org's objects (global describe), so users pick instead of typing an API name.
    export async function sobject(auth: RT.Salesforce) {
      const apiVersion = auth.api_version || "v60.0"
      const response = await fetch(
        `${auth.instance_url}/services/data/${apiVersion}/sobjects/`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { sobjects } = (await response.json()) as {
        sobjects: { name: string; label: string }[]
      }
      return sobjects
        .map((o) => ({ value: o.name, label: `${o.label} (${o.name})` }))
        .sort((a, b) => a.label.localeCompare(b.label))
    }
    
    /**
     * Upsert Record
     * Create or update a record matched by an external ID field. Returns 201 (created) or 200 (updated); the external id field must be marked External ID on the object.
     */
    export async function main(
      auth: RT.Salesforce,
      sobject: DynSelect_sobject,
      external_id_field: string,
      external_id_value: string,
      body: { [key: string]: any }
    ) {
      const apiVersion = auth.api_version || "v60.0"
      const url = new URL(
        `${auth.instance_url}/services/data/${apiVersion}/sobjects/${sobject}/${external_id_field}/${external_id_value}`
      )
    
      const response = await fetch(url, {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      if (response.status === 204) {
        return { success: true }
      }
      return await response.json()
    }
    

    Submitted by hugo989 9 days ago