Edits history of script submission #23360 for ' Create Custom Field Options (jira)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    async function get(auth: RT.Jira, path: string) {
      const response = await fetch(`https://${auth.domain}.atlassian.net${path}`, {
        headers: {
          Authorization: `Basic ${btoa(`${auth.username}:${auth.password}`)}`,
          Accept: "application/json",
        },
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      return await response.json()
    }
    
    export type DynSelect_field_id = string
    
    // Resolver: the site's custom fields (first 100).
    export async function field_id(auth: RT.Jira) {
      const { values } = await get(
        auth,
        "/rest/api/3/field/search?type=custom&maxResults=100"
      )
      return values.map((f: { id: string; name: string }) => ({
        value: f.id,
        label: `${f.name} (${f.id})`,
      }))
    }
    
    export type DynSelect_context_id = string
    
    // Resolver: the contexts of the chosen custom field.
    export async function context_id(auth: RT.Jira, field_id: string) {
      if (!field_id) return []
      const { values } = await get(auth, `/rest/api/3/field/${field_id}/context`)
      return values.map((c: { id: string; name: string }) => ({
        value: c.id,
        label: c.name,
      }))
    }
    
    /**
     * Create Custom Field Options
     * Add options to a select-type custom field in one of its contexts. Requires the Administer Jira permission.
     */
    export async function main(
      auth: RT.Jira,
      field_id: DynSelect_field_id,
      context_id: DynSelect_context_id,
      options: { value: string; disabled?: boolean; optionId?: string }[]
    ) {
      const url = new URL(
        `https://${auth.domain}.atlassian.net/rest/api/3/field/${field_id}/context/${context_id}/option`
      )
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: `Basic ${btoa(`${auth.username}:${auth.password}`)}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({ options }),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 5 hours ago