Edits history of script submission #24032 for ' Create change request (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}`)}`
    }
    
    // Change Management API fields come back as { value, display_value }.
    function value(field: any) {
      return field != null && typeof field === "object" ? field.value : field
    }
    
    function label(field: any) {
      return field != null && typeof field === "object"
        ? field.display_value
        : field
    }
    
    /**
     * Create Change Request
     * Create a normal, emergency or standard change request through the Change Management API (/api/sn_chg_rest, documented in the Yokohama and Brazil API references; needs the itil, change_manager or admin role). A standard change takes the sys_id of a standard change template (std_change_record_producer), whose description and plans cannot be overridden. Reference fields (assignment_group, cmdb_ci) take sys_ids; dates use 'YYYY-MM-DD HH:MM:SS' in UTC. Returns sys_id, number, state and the full record; fields ServiceNow did not apply are listed in ignored_fields.
     */
    export async function main(
      auth: RT.Servicenow,
      type: "normal" | "emergency" | "standard",
      short_description: string,
      standard_change_template_id: string | undefined,
      description: string | undefined,
      assignment_group: string | undefined,
      cmdb_ci: string | undefined,
      start_date: string | undefined,
      end_date: string | undefined,
      fields: { [key: string]: any } | undefined
    ) {
      let path: string
      if (type === "standard") {
        if (!standard_change_template_id) {
          throw new Error(
            "standard_change_template_id is required for a standard change"
          )
        }
        path = `change/standard/${encodeURIComponent(standard_change_template_id)}`
      } else if (type === "normal" || type === "emergency") {
        path = `change/${type}`
      } else {
        throw new Error(`Unknown change type: ${type}`)
      }
    
      // The create endpoints take the record fields as query parameters, not a JSON body.
      const url = new URL(`${auth.instance_url}/api/sn_chg_rest/${path}`)
      const values: { [key: string]: any } = {
        ...(fields ?? {}),
        short_description,
        description,
        assignment_group,
        cmdb_ci,
        start_date,
        end_date,
      }
      for (const [key, v] of Object.entries(values)) {
        if (v != null && v !== "") {
          url.searchParams.append(
            key,
            typeof v === "object" ? JSON.stringify(v) : String(v)
          )
        }
      }
    
      const response = await fetch(url, {
        method: "POST",
        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: any }
      return {
        sys_id: value(result.sys_id),
        number: value(result.number),
        state: value(result.state),
        state_label: label(result.state),
        ignored_fields: result.__meta?.ignoredFields ?? [],
        record: result,
      }
    }
    

    Submitted by hugo989 7 hours ago