Forge repo instructions - 06-use-product-context-solution

Use the work item summary as the dog breed

Make the dog breed dynamic by capturing the work item summary. We’ll utilize the product context data to get the work item details and pass them to the API call.

Utilize the product context in the resolver

  1. In src/resolvers/index.js, update the getDogInfo definition to reference the context argument

    resolver.define('getDogInfo', async ({context}) => {
    
      return (await fetchDogInfo());
    
    });   
    
    
  2. Pass context to the fetchDogInfo function

    resolver.define('getDogInfo', async ({context}) => {
    
      return (await fetchDogInfo(context));
    
    });   
    
    
  3. Update fetchDogInfo function by adding a parameter to handle context

    const fetchDogInfo = async (context) => {
      ...
    }
    
    
  4. In fetchDogInfo get the issue ID from the context parameter

    const fetchDogInfo = async (context) => {
    
        const issueId = context.extension.issue.id;
    
        // Hardcoded for now
        const breedName = "chihuahua"; 
        const apiKey = process.env.API_TOKEN;
        const url = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent(breedName)}`;
    
      ...
    }
    
    

Call a Jira product REST API to get the summary

  1. To call a product REST APIs, we need to import first add it to the import api and route in the src/resolvers/index.js

    import api, { fetch, route } from '@forge/api';
    
    
  2. Create a function called getIssueSummary that will return the issue summary given an issue ID. We’ll use the user’s context via asUser and calling the convenience method requestJira to get the information we need from Jira.

    We’ll use the Get Issue REST API to retrieve the work item details.

    const getIssueSummary = async (issueId) => {
      const response = await api
        .asUser()
        .requestJira(
          route`/rest/api/3/issue/${issueId}?fields=summary`
        );
    
      if (!response.ok) {
        throw new Error(`Unable to retrieve ${issueId}: ${response.status}`);
      }
    
      const issue = await response.json();
    
      return  issue.fields.summary;
    
    }
    
    
  3. Call getIssueSummary in the fetchDogInfo function, and assign the response to our existing breedName variable.

    const fetchDogInfo = async (context) => {
    
        const issueId = context.extension.issue.id;
    
        // Hardcoded for now
        // const breedName = "chihuahua"; 
        const breedName = await getIssueSummary(issueId);
        const apiKey = process.env.API_TOKEN;
        const url = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent(breedName)}`;
    
      ...
    }
    
    

Deploy the changes

  1. Deploy the changes by running this Forge CLI command in your terminal / command line

    forge deploy
    
    
  2. You will get an error, as expected. Let’s fix that using the linter

    forge lint --fix
    
    
  3. Check your manifest.yml and verify if the necessary scope read:jira-work has been added

    permissions:
      external:
        fetch:
          backend:
            - address: api.api-ninjas.com
        images:
          - address: api-ninjas.com
      scopes:
        - read:jira-work
    
    
  4. Now that the error has been fixed, you can now proceed with the deployment and installation upgrade. Since there are changes with the permissions that would trigger a major version update, let’s add that approve flag to the deployment.

    forge deploy --approve MAJOR_VERSION_RULE
    
    
    forge install --upgrade
    
    
  5. Once installation upgrade is done, verify that your app is working as expected. NOTE If your work item summary is a valid dog breed that exists in API Ninjas list, then you will see your dog together with the details, otherwise, it will be an empty panel.

Bonus exercise

  1. Let us add error handling when the dog breed does not exist. In src/resolvers/index.js, update fetchDogInfo to verify if there is a valid API response. Add this code snippet between parsing the response and returning dogInfo,

    ...
    
    const dogInfo = await response.json();
    
    // If the API returned an empty array, the breed name from the issue summary
    // didn't match any results. Fall back to fetching info for a labrador retriever instead.
    if (dogInfo.length === 0) {
      const fallbackUrl = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent('labrador')}`;
      const fallbackResponse = await fetch(fallbackUrl, {
        headers: { 'X-Api-Key': apiKey },
      });
    
      if (!fallbackResponse.ok) {
        throw new Error(`Dogs API fallback returned status ${fallbackResponse.status}`);
      }
    
      const fallbackDogInfo = await fallbackResponse.json();
      console.log('Breed not found, returning labrador retriever as fallback:', fallbackDogInfo);
      return fallbackDogInfo;
    }
    
    return dogInfo;
    
    

    Your fetchDogInfo should look like this,

    const fetchDogInfo = async (context) => {
    
        const issueId = context.extension.issue.id;
    
        // Hardcoded for now
        const breedName = await getIssueSummary(issueId);; 
        const apiKey = process.env.API_TOKEN;
        const url = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent(breedName)}`;
    
        const response = await fetch(url, {
          headers: { 'X-Api-Key': apiKey },
        });
    
        // Handle the negative response of the API call
        if (!response.ok) {
          if (response.status === 429) {
            throw new Error('API rate limit reached. Please try again later.');
          }
          throw new Error(`Dogs API returned status ${response.status}`);
        }
    
        const dogInfo = await response.json();
    
        // If the API returned an empty array, the breed name from the issue summary
        // didn't match any results. Fall back to fetching info for a labrador retriever instead.
        if (dogInfo.length === 0) {
          const fallbackUrl = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent('labrador')}`;
          const fallbackResponse = await fetch(fallbackUrl, {
            headers: { 'X-Api-Key': apiKey },
          });
    
          if (!fallbackResponse.ok) {
            throw new Error(`Dogs API fallback returned status ${fallbackResponse.status}`);
          }
    
          const fallbackDogInfo = await fallbackResponse.json();
          console.log('Breed not found, returning labrador retriever as fallback:', fallbackDogInfo);
          return fallbackDogInfo;
        }
    
        return dogInfo;
    
    }
    
    
  2. Save the changes and do a forge deploy in your terminal.