1 | |
2 |
|
3 | export type DynSelect_table = string |
4 |
|
5 | function authHeader(auth: RT.Servicenow) { |
6 | return auth.token |
7 | ? `Bearer ${auth.token}` |
8 | : `Basic ${btoa(`${auth.username}:${auth.password}`)}` |
9 | } |
10 |
|
11 | |
12 | export async function table(auth: RT.Servicenow) { |
13 | const response = await fetch( |
14 | `${auth.instance_url}/api/now/table/sys_db_object?sysparm_fields=name,label&sysparm_limit=10000`, |
15 | { |
16 | headers: { |
17 | Authorization: authHeader(auth), |
18 | Accept: "application/json", |
19 | }, |
20 | } |
21 | ) |
22 | if (!response.ok) { |
23 | throw new Error(`${response.status} ${await response.text()}`) |
24 | } |
25 | const { result } = (await response.json()) as { |
26 | result: { name: string; label: string }[] |
27 | } |
28 | return result |
29 | .filter((t) => t.name) |
30 | .map((t) => ({ value: t.name, label: `${t.label} (${t.name})` })) |
31 | .sort((a, b) => a.label.localeCompare(b.label)) |
32 | } |
33 |
|
34 | |
35 | * Update Record |
36 | * Update a record by sys_id with a column/value map. PATCH (partial update) by default; set replace=true to PUT (full overwrite that clears omitted fields). |
37 | */ |
38 | export async function main( |
39 | auth: RT.Servicenow, |
40 | table: DynSelect_table, |
41 | sys_id: string, |
42 | body: { [key: string]: any }, |
43 | replace: boolean | undefined |
44 | ) { |
45 | const url = new URL(`${auth.instance_url}/api/now/table/${table}/${sys_id}`) |
46 |
|
47 | const response = await fetch(url, { |
48 | method: replace ? "PUT" : "PATCH", |
49 | headers: { |
50 | Authorization: authHeader(auth), |
51 | "Content-Type": "application/json", |
52 | Accept: "application/json", |
53 | }, |
54 | body: JSON.stringify(body), |
55 | }) |
56 |
|
57 | if (!response.ok) { |
58 | throw new Error(`${response.status} ${await response.text()}`) |
59 | } |
60 |
|
61 | return await response.json() |
62 | } |
63 |
|