Edits history of script submission #24033 for ' Create incident (servicenow)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    function authHeader(auth: RT.Servicenow) {
      return auth.token
        ? `Bearer ${auth.token}`
        : `Basic ${btoa(`${auth.username}:${auth.password}`)}`
    }
    
    /**
     * Create Incident
     * Open an incident (Table API, POST /api/now/table/incident). Set impact and urgency (default choices 1 = High, 2 = Medium, 3 = Low): ServiceNow computes the priority from them, so priority is not an input. Reference fields (cmdb_ci, assignment_group, caller) take sys_ids. Returns sys_id, number, priority and the full record.
     */
    export async function main(
      auth: RT.Servicenow,
      short_description: string,
      description: string | undefined,
      impact: string | undefined,
      urgency: string | undefined,
      cmdb_ci: string | undefined,
      assignment_group: string | undefined,
      caller: string | undefined,
      fields: { [key: string]: any } | undefined
    ) {
      const url = new URL(`${auth.instance_url}/api/now/table/incident`)
    
      const body: { [key: string]: any } = { ...(fields ?? {}) }
      const values: { [key: string]: string | undefined } = {
        short_description,
        description,
        impact,
        urgency,
        cmdb_ci,
        assignment_group,
        caller_id: caller,
      }
      for (const [key, v] of Object.entries(values)) {
        if (v != null && v !== "") body[key] = v
      }
    
      const response = await fetch(url, {
        method: "POST",
        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()}`)
      }
    
      const { result } = (await response.json()) as { result: any }
      return {
        sys_id: result.sys_id,
        number: result.number,
        priority: result.priority,
        record: result,
      }
    }
    

    Submitted by hugo989 7 hours ago