0

Update Record

by
Published 8 days ago

Update fields on an existing record by ID. Salesforce returns 204 No Content on success, so this returns {success, id}.

Script salesforce Verified

The script

Submitted by hugo989 Bun
Verified 9 days ago
1
//native
2

3
export type DynSelect_sobject = string
4

5
// Dropdown of the org's objects (global describe), so users pick instead of typing an API name.
6
export async function sobject(auth: RT.Salesforce) {
7
  const apiVersion = auth.api_version || "v60.0"
8
  const response = await fetch(
9
    `${auth.instance_url}/services/data/${apiVersion}/sobjects/`,
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  if (!response.ok) {
18
    throw new Error(`${response.status} ${await response.text()}`)
19
  }
20
  const { sobjects } = (await response.json()) as {
21
    sobjects: { name: string; label: string }[]
22
  }
23
  return sobjects
24
    .map((o) => ({ value: o.name, label: `${o.label} (${o.name})` }))
25
    .sort((a, b) => a.label.localeCompare(b.label))
26
}
27

28
/**
29
 * Update Record
30
 * Update fields on an existing record by ID. Salesforce returns 204 No Content on success, so this returns {success, id}.
31
 */
32
export async function main(
33
  auth: RT.Salesforce,
34
  sobject: DynSelect_sobject,
35
  record_id: string,
36
  body: { [key: string]: any }
37
) {
38
  const apiVersion = auth.api_version || "v60.0"
39
  const url = new URL(
40
    `${auth.instance_url}/services/data/${apiVersion}/sobjects/${sobject}/${record_id}`
41
  )
42

43
  const response = await fetch(url, {
44
    method: "PATCH",
45
    headers: {
46
      Authorization: `Bearer ${auth.token}`,
47
      "Content-Type": "application/json",
48
      Accept: "application/json",
49
    },
50
    body: JSON.stringify(body),
51
  })
52

53
  if (!response.ok) {
54
    throw new Error(`${response.status} ${await response.text()}`)
55
  }
56

57
  return { success: true, id: record_id }
58
}
59