Edits history of script submission #22734 for ' Update Record (servicenow)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    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))
    }
    
    /**
     * Update Record
     * 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).
     */
    export async function main(
      auth: RT.Servicenow,
      table: DynSelect_table,
      sys_id: string,
      body: { [key: string]: any },
      replace: boolean | undefined
    ) {
      const url = new URL(`${auth.instance_url}/api/now/table/${table}/${sys_id}`)
    
      const response = await fetch(url, {
        method: replace ? "PUT" : "PATCH",
        headers: {
          Authorization: authHeader(auth),
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 5 days ago