Trying to create a issue in one jira instance from another instance

resolver.define('createIssue', async () => {
  try {
    const bodyData = {
      fields: {
        project: {
          key: 'FL',  // Project key in the target Jira instance
        },
        summary: 'Issue has been created',  // Issue summary
        issuetype: {
          name: 'Task',
        },
        description: 'This issue is related to a Forge integration',  // Issue description (plain text)
      },
    };

    const targetJiraUrl = 'https://forge-learning1.atlassian.net/';
    const authHeader = {
      'Authorization': 'Basic ' + Buffer.from('user@email.com' + ':' + 'my-auth-token').toString('base64'),
    };
   
    const response = await fetch(`${targetJiraUrl}/rest/api/2/issue`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        ...authHeader,
      },
      body: JSON.stringify(bodyData),
    });
  // const data = await response.json()
  // console.log(data, "data")
    console.log('Response Status:', response.status);
    console.log('Response OK:', response.ok);
      
      // console.log(response.json(), "json")
      // const check = await response.json()
      // console.log(check," cjeckk")
    // If response.ok is true, try to consume the body manually
    if (response.ok) {
      console.log('Response is okay');
      try {
        // Try consuming the body as text and then parse it as JSON if possible
        const responseBody = await JSON.parse( response.text());  // Consume the body as text
        console.log('Raw Response Body:', responseBody);  // Log the raw response body

        // Parse it into JSON if possible
        const issue = JSON.parse(responseBody);  // Attempt to parse the raw body into JSON
        console.log('Created issue:', issue);
        return issue;
      } catch (error) {
        console.error('Error parsing response body:', error);
        throw new Error('Failed to parse the response body');
      }
    }

    // If the response is not OK, handle error
    const errorBody = await response.text();
    console.error('Error response body:', errorBody);
    throw new Error(`Failed to create issue in target Jira instance: ${response.statusText}`);

  } catch (error) {
    console.error('Error creating issue:', error);
    throw new Error('Failed to create issue in the target Jira instance');
  }
});   

the issue is being created but the function is not returning the issue when trying to log response.body i get

ReadableStream { locked: false, state: 'errored', supportsBYOB: true } body  11:11:31.663  fbe8c66a-9a97-4108-a71f-ce794414ecd2  Error creating issue: TypeError: Body is unusable: Body has already been read

Hi @Ankitkharola. You can only call response.text() once. So, either place it higher up and insure that it’s not called twice… or implement an else block where (where you’re declaring errorBody).

2 Likes

@nmansilla Thank you sir