Course menuForge Cloud

Level 1 · Lesson 6

Read the repair task

Goal of this lesson

Read the car from the work item’s own summary, as the person looking at it, and let forge lint add the permission that needs.

About 30 min6 steps

Behind, or starting here? Download the code as it should be before this lesson, or in the course workspace run course-catch-up level-1/after-05-lay-out-the-car-details-card in the folder above your app. It offers to bring your own app folder to this point and keeps its app id (the id: line in manifest.yml, which links the code to your app on the site), so it stays the same app. Your old files are kept in a copy next to it.

The card still looks up a BMW 3 Series on every repair task. This lesson makes the resolver read the summary of the repair task the card is on, and take the make and model from it. That means a call into Jira, and Jira has its own rules about who may read what.

Step 1: Bring in the Jira API

Atlassian’s own products

Product REST APIs

Jira and Confluence have REST APIs, sets of web addresses your code can read and write through, for everything you see on screen: work items, comments, pages. From a function you call them through @forge/api, with requestJira or requestConfluence, and a path built with the route tag. Forge adds the authentication; you never handle a Jira token.

Further reading, optional: Atlassian docs on Product REST APIs (opens in a new tab)

The package is already installed from lesson 4. This time the file borrows two more things from it: api, the package’s main tool for talking to Jira and Confluence, and route, a helper for building Jira addresses safely. The import line at the top of a file is simply its list of what it borrows:

Editsrc/resolvers/index.js

api and route come from @forge/api.

import Resolver from '@forge/resolver';
Added: import api, { route } from '@forge/api';

Borrow api, for calling Jira, and route, for building Jira addresses safely.

import { findCar } from '../cars/apiNinjas';
const resolver = new Resolver();

Why: Product REST APIs

Stuck?One common problem, and its fix
  • “Cannot find module @forge/…”

    The code imports a package that is not installed. Install the one named in the message, then deploy:

    RunTerminal
    npm install @forge/api
    forge deploy
    Open in the FAQ

Step 2: Read the summary on your own login

Runs in the Atlassian cloud

asUser()in the workshop: on your own login

asUser() makes the call as the person using the app, with exactly their permissions. If they cannot see a work item, neither can your code. The first time someone uses an asUser() call, Jira asks them to allow the app to act for them. Its opposite, asApp(), acts as the app itself; Level 2 needs it for work that runs with nobody watching.

In the workshop The app acts on the login of the person who asked, and can only see and do what they can.

Further reading, optional: Atlassian docs on Product REST APIs (opens in a new tab)

See this on the Level 1 chart, in the step that reads the work item.

Add a helper that asks Jira for one work item, with only the summary field:

Editsrc/resolvers/index.js

A helper that asks Jira for one work item’s summary.

const resolver = new Resolver();
Added: // Ask Jira for the work item's summary, with the permissions of the person viewing it.
Added: async function readSummary(issueId) {

A helper that takes a work item’s id and gives back its summary.

Added: const response = await api.asUser().requestJira(route`/rest/api/3/issue/${issueId}?fields=summary`);

Ask Jira for that work item, only its summary field, as the person looking at the card, and wait for the answer.

Added: if (!response.ok) {

Jira said no, for example 404 when the person can’t see the work item: stop, with the status in the message.

Added: throw new Error(`Jira answered ${response.status} for this work item.`);
Added: }
Added: const issue = await response.json();
Added: return issue.fields.summary;

Read the JSON answer and give back just the summary.

Added: }
Added:
resolver.define('getCar', async () => {
const make = 'BMW';
const model = '3 Series';

Why: asUser() · Product REST APIs

In plain words: the function asks Jira for /rest/api/3/issue/ followed by the work item’s id, and only for its summary field, as the person looking at the card. Then it checks the status code from lesson 4 and takes the summary out of the answer.

route makes the id safe to put in a web address, so a strange id can never change which address is asked. A non-OK answer becomes an error with the status in it. The one you are most likely to meet is 404, “not found”: Jira answers it when the work item doesn’t exist, and also when the person may not see it, so that it gives nothing away.

Stuck?One common problem, and its fix
  • The app asks me to “Allow access”

    Apps that call Jira or Confluence on your own login (asUser()) need your consent once per person. Select Allow access, accept, and reload.

    Open in the FAQ

Step 3: Look up the car on the repair task

Runs in the Atlassian cloud

Product contextin the workshop: the task number

Every resolver call arrives with a context that Forge fills in: who is calling, from which site, and from where in the product. On an issue panel, context.extension.issue holds the work item’s id and key. The browser cannot change it, so it is the right source for which repair task to read.

In the workshop Every request says which repair task the car details card is on.

Further reading, optional: Atlassian docs on App context security (opens in a new tab)

A repair task’s summary is the car’s make and model, a dash, then the repair: BMW 3 Series – grinding noise from front. Add a small helper, a short function that does one thing and that other code calls, that splits it into three parts. It cuts at the first dash with a space on each side, so the hyphen in a make such as Mercedes-Benz stays. The first word is the make and the rest is the model, except for the few makes of two words it lists:

New filesrc/cars/summary.js

A new file: the make and model come before the first spaced dash, the repair after it.

Added: // Reads a repair task summary such as "BMW 3 Series – grinding noise from front".
Added: // The car is everything before the first spaced dash (" – " or " - "), so a
Added: // hyphen inside a name, as in Mercedes-Benz, stays. Its first word is the make and
Added: // the rest is the model, except for the makes of two words listed here.
Added: const TWO_WORD_MAKES = ['Land Rover', 'Alfa Romeo', 'Aston Martin'];

The makes whose name is two words, so the helper doesn’t take “Land” as the make and “Rover Defender” as the model.

Added:
Added: export function splitSummary(summary) {

Take a summary and give back its parts: the car’s name, make, model and the repair.

Added: const text = String(summary ?? '').trim();
Added: const dash = text.match(/\s[–-]\s/);

Find the first dash with a space on each side. The slashes hold a search pattern: \s is a space, [–-] is either kind of dash.

Added: const name = (dash ? text.slice(0, dash.index) : text).trim();

Everything before that dash is the car’s name. No dash: the whole summary is.

Added: const repair = dash ? text.slice(dash.index + dash[0].length).trim() : '';

Everything after the dash is the repair.

Added: const twoWord = TWO_WORD_MAKES.find((make) => name.toLowerCase().startsWith(`${make.toLowerCase()} `));
Added: const make = twoWord ?? name.split(/\s+/)[0];

The make is the two-word make if one matched, otherwise the first word.

Added: const model = name.slice(make.length).trim();

The model is whatever comes after the make.

Added: return { name, make, model, repair };
Added: }

Why: Jira work item

API Ninjas could tell you which makes exist, but its list of makes is for premium subscribers, so the helper keeps its own short list. Anything it cannot read, such as a summary with no model, ends in the card’s “nothing found” state.

Now replace the fixed car with the repair task’s summary, and show the repair above what the car comes in:

Editsrc/frontend/index.jsxChange 1 of 5
  • Take the work item id from the context, not from the browser, and read its summary.
  • Show the repair above what the car comes in.
<Heading size="medium">{`${car.make} ${car.model}`}</Heading>
{car.since && <Lozenge>{`Since ${car.since}`}</Lozenge>}
</Inline>
Added: {result.repair && <Text>{`Repair: ${result.repair}`}</Text>}

Show the repair, when the summary has one.

<Heading size="small">Comes in</Heading>
<List type="unordered">
{facts.map(([name, values]) => (
Editsrc/resolvers/index.jsChange 2 of 5
import Resolver from '@forge/resolver';
import api, { route } from '@forge/api';
import { findCar } from '../cars/apiNinjas';
Added: import { splitSummary } from '../cars/summary';

Borrow the new summary helper.

const resolver = new Resolver();
Editsrc/resolvers/index.jsChange 3 of 5
return issue.fields.summary;
}
Removed: resolver.define('getCar', async () => {
Removed: const make = 'BMW';
Removed: const model = '3 Series';
Removed: const query = `${make} ${model}`;
Added: resolver.define('getCar', async ({ context }) => {

The same question as before, now also receiving the context Forge sends with every call.

Added: const { name, make, model, repair } = splitSummary(await readSummary(context.extension.issue.id));

Read the summary of the work item the card is on, then split it into its parts.

Added: if (!model) return { query: name, repair, car: null };

No model in the summary: don’t ask API Ninjas at all, answer “no car” straight away.

try {
const car = await findCar(make, model, process.env.API_NINJAS_KEY);
Editsrc/resolvers/index.jsChange 4 of 5
try {
const car = await findCar(make, model, process.env.API_NINJAS_KEY);
Removed: return { query, car };
Added: return { query: name, repair, car };
} catch (error) {
Editsrc/resolvers/index.jsChange 5 of 5
} catch (error) {
Removed: console.error(`Car lookup failed for "${query}":`, error);
Removed: return { query, car: null, error: error.message };
Added: console.error(`Car lookup failed for "${name}":`, error);
Added: return { query: name, repair, car: null, error: error.message };
}
});

Why: Product context

The card could have sent the work item id in invoke() instead, but anything the browser sends can be changed by the person using it: browsers have built-in developer tools that let anyone edit a page’s code and requests before they are sent. The context is filled in by Forge, outside the browser, so nobody can tamper with it.

BrowserCar details cardForgeadds the contextYour resolverinvoke()contextwhich work iteman id the browser sendsanyone can edit it
Stuck?One common problem, and its fix
  • The card says there is no car data for my work item

    The card reads the make and model from the start of the summary, before the first dash with a space on each side. Start the summary with a car the service knows, such as “Volkswagen Golf – oil service”, and reload. Makes of two words, such as Land Rover, work only if the helper in src/cars/summary.js lists them.

    Open in the FAQ

Step 4: Let the linter add the permission

Declared in manifest.yml

Scopein the workshop: a line on the signed approval

A scope is a permission to use part of a product API, such as read:jira-work for reading work items. The app declares its scopes under permissions.scopes, the admin agrees to them at install, and Forge refuses any API call the scopes do not cover, even if the person could do it themselves.

In the workshop Each line the customer signed covers one kind of work; anything not on it is refused.

Further reading, optional: Atlassian docs on Permissions (opens in a new tab)

Lives on your laptop

forge lint

forge lint checks the manifest and code before a deploy and reports problems, such as an API call with no matching scope. forge lint --fix adds what it can work out for you. forge deploy runs the same checks first.

The new call reads Jira, and the manifest has no scope for that yet. Ask the linter:

RunTerminal
forge lint

It reports one problem: your code calls the Jira API, but the manifest has no scope that allows it. That is the problem this step fixes, not something you did wrong.

You should seeExampleAn example: your line and column numbers, and the exact wording, may differ.
$ forge lint
/src/resolvers/index.js
  10:50  error  Jira endpoint: GET /rest/api/3/issue/{issueIdOrKey} requires "read:jira-work" scope  permission-scope-required
X 1 issue (1 error, 0 warnings, 0 approvals)
  Run forge lint --fix to automatically fix 1 error and 0 warnings.

Current CLI versions show it in red as an error and won’t deploy until it is fixed; older ones called it a warning. Either way it is this missing permission, which the next command fixes. Without the scope, the call would be refused when the card runs. Let the linter write the missing line:

RunTerminal
forge lint --fix
You should seeExampleAn example.
$ forge lint --fix
✔ Fixed 1 error and 0 warnings
Run forge lint to review outstanding errors and warnings
Editmanifest.yml

forge lint --fix writes this for you.

fetch:
backend:
- address: api.api-ninjas.com
Added: scopes:
Added: - read:jira-work

Permission to read work items. forge lint --fix wrote this line.

Why: Scope · forge lint

Stuck?2 common problems, and their fixes
  • I added a scope or an outside host

    A permission change makes a new major version. Approve it, then move each installation onto it:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade

    If the app is installed on Jira and Confluence, run the upgrade for each; it asks which installation.

    Open in the FAQ
  • After changing manifest.yml, forge lint or forge deploy reports an error in the manifest

    Most often the spaces at the start of the lines are off. In manifest.yml those spaces matter: they show what belongs inside what, the way an outline does. Every line you add must start with exactly as many spaces as the line it sits next to in the lesson’s change, and it must use spaces, not tabs. Compare your file with the change, line up the new lines, save, and run:

    RunTerminal
    forge lint

    If you are still stuck, download the code after the lesson (the link at the end of each lesson) and compare its manifest.yml with yours.

    Open in the FAQ

Step 5: Sign the new approval again

A new scope is a new permission, so this is a major version again. Stop the tunnel if it runs, then:

RunTerminal
forge deploy --approve MAJOR_VERSION_RULE
forge install --upgrade

The upgrade looks as it did in lesson 4: pick your site’s row in the table, then answer y to both questions (Enter alone means No). This time it lists the new scope, read:jira-work, instead of an address.

Reload the BMW 3 Series repair task. Because the resolver now reads Jira as you, the card may first ask you to allow the app to act for you. If it does, allow it once. If the card shows the repair line and the specs straight away, that is fine too: as the site admin you may already have approved it during the upgrade.

Stuck?3 common problems, and their fixes
  • Deploy stops after a permission change

    That is expected, not an error. A new scope or outside host makes a new major version, which you approve. Then move each installation onto it. On your own developer site you are the admin, so you accept it yourself:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade
    Open in the FAQ
  • The app asks me to “Allow access”

    Apps that call Jira or Confluence on your own login (asUser()) need your consent once per person. Select Allow access, accept, and reload.

    Open in the FAQ
  • The tunnel is running while I deploy or upgrade

    Stop it with Ctrl+C first, then deploy or upgrade, then start it again. While the tunnel runs, Jira runs the code on your laptop instead of your last deploy, so if you deploy with it running you cannot tell which version you are testing. Changes to the manifest only reach the site through a deploy, never through the tunnel.

    Open in the FAQ

Step 6: Try other repair tasks

  1. Create two more repair tasks in the Workshop space, such as Volkswagen Golf – oil service and Toyota Corolla – squeaking brakes, and open each one.
  2. On a new work item the panel isn’t there yet: add it once from the View app actions icon under the title, as in lesson 1, but choose Car details: the menu shows the panel’s title, which you changed from Workshop helper in lesson 2.

Each card shows its own car and its own repair.

Rename one so it names no car the service knows, such as Moon Buggy – flat tyre. The card shows the information message with the car in it: the empty state from lesson 5, now read from a real repair task.

Stuck?2 common problems, and their fixes
  • The card says there is no car data for my work item

    The card reads the make and model from the start of the summary, before the first dash with a space on each side. Start the summary with a car the service knows, such as “Volkswagen Golf – oil service”, and reload. Makes of two words, such as Land Rover, work only if the helper in src/cars/summary.js lists them.

    Open in the FAQ
  • I can’t see the car details card on the work item

    Check that the app is installed on the site you are looking at (forge install list). Then open a work item and look under its title for a small icon called View app actions (hover over the icons to see their names); select it, then Car details. Issue panels are added this way once per work item, so every new work item needs it once. The panel can take about ten seconds to load the first time, and shows a DEV badge because you are running the development version.

    Open in the FAQ

Compare with yours: download the code after this lesson.

Type at least two letters.