import * as wmill from "windmill-client"
import { S3Object } from "windmill-client"
export type DynSelect_table = string
function authHeader(auth: RT.Servicenow) {
return auth.token
? `Bearer ${auth.token}`
: `Basic ${btoa(`${auth.username}:${auth.password}`)}`
}
// Dropdown of the instance's tables (sys_db_object).
export async function table(auth: RT.Servicenow) {
const response = await fetch(
`${auth.instance_url}/api/now/table/sys_db_object?sysparm_fields=name,label&sysparm_limit=10000`,
{
headers: {
Authorization: authHeader(auth),
Accept: "application/json",
},
}
)
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { result } = (await response.json()) as {
result: { name: string; label: string }[]
}
return result
.filter((t) => t.name)
.map((t) => ({ value: t.name, label: `${t.label} (${t.name})` }))
.sort((a, b) => a.label.localeCompare(b.label))
}
/**
* Upload Attachment
* Attach a file from Windmill object storage to a record. Reads the bytes and posts them to the Attachment API (table_name, table_sys_id, file_name in the query string; raw body).
*/
export async function main(
auth: RT.Servicenow,
table: DynSelect_table,
record_sys_id: string,
file: S3Object,
file_name: string,
content_type: string | undefined
) {
const bytes = await wmill.loadS3File(file)
if (!bytes) {
throw new Error("Could not load the file from object storage")
}
const url = new URL(`${auth.instance_url}/api/now/attachment/file`)
url.searchParams.append("table_name", table)
url.searchParams.append("table_sys_id", record_sys_id)
url.searchParams.append("file_name", file_name)
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: authHeader(auth),
"Content-Type":
content_type && content_type !== ""
? content_type
: "application/octet-stream",
Accept: "application/json",
},
body: bytes,
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
Submitted by hugo989 5 days ago