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
-
In
src/resolvers/index.js, update thegetDogInfodefinition to reference thecontextargumentresolver.define('getDogInfo', async ({context}) => { return (await fetchDogInfo()); }); -
Pass
contextto thefetchDogInfofunctionresolver.define('getDogInfo', async ({context}) => { return (await fetchDogInfo(context)); }); -
Update
fetchDogInfofunction by adding a parameter to handlecontextconst fetchDogInfo = async (context) => { ... } -
In
fetchDogInfoget the issue ID from the context parameterconst 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
-
To call a product REST APIs, we need to import first add it to the import
apiandroutein thesrc/resolvers/index.jsimport api, { fetch, route } from '@forge/api'; -
Create a function called
getIssueSummarythat will return the issue summary given an issue ID. We’ll use the user’s context viaasUserand calling the convenience methodrequestJirato 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; } -
Call
getIssueSummaryin thefetchDogInfofunction, and assign the response to our existingbreedNamevariable.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
-
Deploy the changes by running this Forge CLI command in your terminal / command line
forge deploy -
You will get an error, as expected. Let’s fix that using the linter
forge lint --fix -
Check your
manifest.ymland verify if the necessary scoperead:jira-workhas been addedpermissions: external: fetch: backend: - address: api.api-ninjas.com images: - address: api-ninjas.com scopes: - read:jira-work -
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
approveflag to the deployment.forge deploy --approve MAJOR_VERSION_RULEforge install --upgrade -
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
-
Let us add error handling when the dog breed does not exist. In
src/resolvers/index.js, updatefetchDogInfoto verify if there is a valid API response. Add this code snippet between parsing the response and returningdogInfo,... 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
fetchDogInfoshould 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; } -
Save the changes and do a
forge deployin your terminal.