//native
import * as wmill from "windmill-client"
/**
* New or Updated Record
* 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).
*/
export async function main(
auth: RT.Salesforce,
sobject: string,
fields: string | undefined
) {
const apiVersion = auth.api_version || "v60.0"
const lastChecked: string | undefined = await wmill.getState()
const selectFields = fields && fields !== "" ? fields : "Id, LastModifiedDate"
let soql = `SELECT ${selectFields} FROM ${sobject}`
if (lastChecked) {
soql += ` WHERE LastModifiedDate > ${lastChecked}`
}
soql += " ORDER BY LastModifiedDate ASC LIMIT 200"
const url = new URL(`${auth.instance_url}/services/data/${apiVersion}/query`)
url.searchParams.append("q", soql)
const response = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer ${auth.token}`,
Accept: "application/json",
},
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const data = await response.json()
const records: Array<{ LastModifiedDate: string }> = data.records ?? []
// SOQL datetime literals must be bare ISO 8601 without fractional seconds; the
// LastModifiedDate Salesforce returns (e.g. ...+0000) is not a valid literal, so normalize.
const toSoql = (d: string) =>
new Date(d).toISOString().replace(/\.\d{3}Z$/, "Z")
// First run: set the watermark to now and don't emit a backlog.
if (!lastChecked) {
await wmill.setState(toSoql(new Date().toISOString()))
return []
}
if (records.length > 0) {
await wmill.setState(toSoql(records[records.length - 1].LastModifiedDate))
}
return records
}
Submitted by hugo989 9 days ago