1 | |
2 |
|
3 | import * as wmill from "windmill-client" |
4 |
|
5 | |
6 | * New or Updated Record |
7 | * Emits records of an object whose LastModifiedDate is newer than the last poll, tracked via Windmill state. Pass an optional comma-separated fields list (defaults to Id, LastModifiedDate). |
8 | */ |
9 | export async function main( |
10 | auth: RT.Salesforce, |
11 | sobject: string, |
12 | fields: string | undefined |
13 | ) { |
14 | const apiVersion = auth.api_version || "v60.0" |
15 | const lastChecked: string | undefined = await wmill.getState() |
16 |
|
17 | const selectFields = fields && fields !== "" ? fields : "Id, LastModifiedDate" |
18 | let soql = `SELECT ${selectFields} FROM ${sobject}` |
19 | if (lastChecked) { |
20 | soql += ` WHERE LastModifiedDate > ${lastChecked}` |
21 | } |
22 | soql += " ORDER BY LastModifiedDate ASC LIMIT 200" |
23 |
|
24 | const url = new URL(`${auth.instance_url}/services/data/${apiVersion}/query`) |
25 | url.searchParams.append("q", soql) |
26 |
|
27 | const response = await fetch(url, { |
28 | method: "GET", |
29 | headers: { |
30 | Authorization: `Bearer ${auth.token}`, |
31 | Accept: "application/json", |
32 | }, |
33 | }) |
34 |
|
35 | if (!response.ok) { |
36 | throw new Error(`${response.status} ${await response.text()}`) |
37 | } |
38 |
|
39 | const data = await response.json() |
40 | const records: Array<{ LastModifiedDate: string }> = data.records ?? [] |
41 |
|
42 | |
43 | |
44 | const toSoql = (d: string) => |
45 | new Date(d).toISOString().replace(/\.\d{3}Z$/, "Z") |
46 |
|
47 | |
48 | if (!lastChecked) { |
49 | await wmill.setState(toSoql(new Date().toISOString())) |
50 | return [] |
51 | } |
52 |
|
53 | if (records.length > 0) { |
54 | await wmill.setState(toSoql(records[records.length - 1].LastModifiedDate)) |
55 | } |
56 |
|
57 | return records |
58 | } |
59 |
|