GithubHelp home page GithubHelp logo

mrrefactoring / jira.js Goto Github PK

View Code? Open in Web Editor NEW
258.0 5.0 45.0 62.56 MB

A JavaScript/TypeScript wrapper for the JIRA Cloud, Service Desk and Agile REST API

Home Page: https://mrrefactoring.github.io/jira.js/

License: MIT License

TypeScript 100.00%
jira jira-client jira-js javascript typescript agile cloud service-desk api rest atlassian nodejs typescipt

jira.js's Introduction

Jira.js logo

NPM version NPM downloads per month build status license

JavaScript / TypeScript library for Node.JS and browsers to easily interact with Atlassian Jira API

About

Jira.js is a powerful Node.JS / Browser module that allows you to interact with the Jira Cloud API, Jira Agile Cloud API, Jira ServiceDesk Cloud API very easily.

Usability, consistency, and performance are key focuses of jira.js, and it also has nearly 100% coverage of the Jira API. It receives new Jira features shortly after they arrive in the API.

Table of Contents

Installation

Node.js 18.0.0 or newer is required.

Install with the npm:

npm install jira.js

Install with the yarn:

yarn add jira.js

Documentation

You can find the documentation here.

Usage

Authentication

There are several types of authentication to gain access to the Jira API. Let's take a look at a few of them below:

Basic authentication allows you to log in with credentials. You can use username and password, but this login method is not supported in the online version and most standalone versions, so it's better to release API Token. Read how to do it here and use it together with email.

Username and password example:

import { Version3Client } from 'jira.js';

const client = new Version3Client({
  host: 'https://your-domain.atlassian.net',
  authentication: {
    basic: {
      username: 'YOUR_USERNAME',
      password: 'YOUR_PASSWORD',
    },
  },
});

Email and API Token example:

import { Version3Client } from 'jira.js';

const client = new Version3Client({
  host: 'https://your-domain.atlassian.net',
  authentication: {
    basic: {
      email: '[email protected]',
      apiToken: 'YOUR_API_TOKEN',
    },
  },
});

Only the authorization token is currently supported. To release it, you need to read the documentation and write your own code to get the token.

Example of usage

import { Version3Client } from 'jira.js';

const client = new Version3Client({
  host: 'https://your-domain.atlassian.net',
  authentication: {
    oauth2: {
      accessToken: 'YOUR_ACCESS_TOKEN',
    },
  },
});
import { Version3Client } from 'jira.js';

const client = new Version3Client({
  host: 'https://your-domain.atlassian.net',
  authentication: {
    personalAccessToken: 'secrectPAT',
  },
});

Example and using algorithm

  1. Example

You can find out examples project here or perform the following actions:

  • Change the host, email and apiToken to your data
  • Run script
import { Version3Client } from 'jira.js';

const client = new Version3Client({
  host,
  authentication: {
    basic: {
      email,
      apiToken,
    },
  },
});

async function main() {
  const projects = await client.projects.getAllProjects();

  if (projects.length) {
    const project = projects[0];

    const { id } = await client.issues.createIssue({
      fields: {
        summary: 'My first issue',
        issuetype: {
          name: 'Task'
        },
        project: {
          key: project.key,
        },
      }
    });

    const issue = await client.issues.getIssue({ issueIdOrKey: id });

    console.log(`Issue '${issue.fields.summary}' was successfully added to '${project.name}' project.`);
  } else {
    const myself = await client.myself.getCurrentUser();

    const { id } = await client.projects.createProject({
      key: 'PROJECT',
      name: "My Project",
      leadAccountId: myself.accountId,
      projectTypeKey: 'software',
    });

    const project = await client.projects.getProject({ projectIdOrKey: id.toString() });

    console.log(`Project '${project.name}' was successfully created.`);
  }
}

main();
  1. The algorithm for using the library:
client.<group>.<methodName>(parametersObject);

Available groups:

Agile Cloud API group
Version 2 Cloud REST API group
Version 3 Cloud REST API group
Service Desk Cloud API group

The name of the methods is the name of the endpoint in the group without spaces and in camelCase.

The parameters depend on the specific endpoint. For more information, see here.

Decreasing Webpack bundle size

If you use Webpack and need to reduce the size of the assembly, you can create your client with only the groups you use.

import { BaseClient } from 'jira.js';
import { Board } from 'jira.js/out/agile';
import { Groups } from 'jira.js/out/version2';
import { Issues } from 'jira.js/out/version3';

export class CustomJiraClient extends BaseClient {
  board = new Board(this);
  groups = new Groups(this);
  issues = new Issues(this);
}

Take a look at our other products

  • Confluence.js - confluence.js is a powerful Node.JS / Browser module that allows you to interact with the Confluence API very easily
  • Trello.js - JavaScript / TypeScript library for Node.JS and browsers to easily interact with Atlassian Trello API

License

Distributed under the MIT License. See LICENSE for more information.

jira.js's People

Contributors

balaprasanna avatar cellule avatar dependabot-preview[bot] avatar dependabot[bot] avatar jayree avatar jbouchard24 avatar jbrunton avatar knor-el-snor avatar logjscript avatar mrrefactoring avatar rdohms avatar swapnull avatar violine1101 avatar vit-lebediev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

jira.js's Issues

when i use issueSearch.searchForIssuesUsingJql

rts.push(${this.encode(key)}=${this.encode(value)});
^

TypeError: Cannot read property 'encode' of undefined
at /home/xxx/Documents/script/work-flow/node_modules/jira.js/src/clients/baseClient.ts:52:26
at Array.forEach ()
at paramSerializer (/home/xxx/Documents/script/work-flow/node_modules/jira.js/src/clients/baseClient.ts:34:32)
at buildURL (/home/xxx/Documents/script/work-flow/node_modules/axios/lib/helpers/buildURL.js:30:24)
at Axios.getUri (/home/xxx/Documents/script/work-flow/node_modules/axios/lib/core/Axios.js:69:10)
at Function.wrap [as getUri] (/home/xxx/Documents/script/work-flow/node_modules/axios/lib/helpers/bind.js:9:15)
at Version3Client. (/home/xxx/Documents/script/work-flow/node_modules/jira.js/src/clients/baseClient.ts:108:32)
at Generator.next ()
at /home/xxx/Documents/script/work-flow/node_modules/jira.js/out/clients/baseClient.js:8:71
at new Promise ()

new Client() timeout description

Hello!
Can you describe or add to documentation anything about "timeout" option ?
It's possible set 0 to avoid timeout for basic auth ?

Jira OAuth 1.0 missing functions

Hi, I see that you have the option to authenticate through OAuth 1.0, which is specially useful for jira server versions above 8.5.x and below 8.10.x but your OAuth1 constructor is expecting:

  • consumerKey
  • consumerSecret
  • accessToken
  • tokenSecret

The problem is that some other requests are necessary to get all these 4 pieces of data. It would be very useful to have the functions that implement the initial requests to get these 4 elements like in the OAuth section of the

Thanks!

Use Custom Agent with SSL Certificate?

Hi there,

first of thanks for implementing this library works really well.
My use case would see the need to use a custom SSL Certificate on every request.
From my understanding of Axios this could be implemented via the Axios Config, but maybe there is a easier solution?

Basic Example:

`
const httpsAgent = new https.Agent({
cert: fs.readFileSync("./usercert.pem"),
key: fs.readFileSync("./key.pem"),
passphrase: "YYY"

const instance = axios.create({ httpsAgent })
})`

Will this be supported in the future?
Im not too familiar with Axios or otherwise I would have diretcly opened a Pull Request.

Best regards,
Niklas

AxiosError ERR_FR_MAX_BODY_LENGTH_EXCEEDED

I'm getting this error, trying to attach the file to the tickets
can we add these two params to the
maxContentLength: Infinity, maxBodyLength: Infinity

to

addAttachment(parameters, callback) { var _a; return tslib_1.__awaiter(this, void 0, void 0, function* () { const formData = new FormData(); const attachments = Array.isArray(parameters.attachment) ? parameters.attachment : [parameters.attachment]; attachments.forEach(attachment => formData.append('file', attachment.file, attachment.filename)); const config = { url:/rest/api/3/issue/${parameters.issueIdOrKey}/attachments, method: 'POST', headers: Object.assign({ 'X-Atlassian-Token': 'no-check', 'Content-Type': 'multipart/form-data' }, (_a = formData.getHeaders) === null || _a === void 0 ? void 0 : _a.call(formData)), data: formData, maxContentLength: Infinity, maxBodyLength: Infinity }; return this.client.sendRequest(config, callback); }); }
in

/jira.js/out/version3/issueAttachments.js

bulkGetUser: accountId parameter doesn't get serialised

Problem:
The accountId param for bulkGetUser should be serialised, just like bulkGetUsersMigration, in order for it to return the correct results. The current version of bulkGetUser can only fetch one user at a time.

Current behaviour & code:
Screenshot 2022-07-02 at 15 34 52
Screenshot 2022-07-02 at 15 31 32

Expected behaviour & code:
Screenshot 2022-07-02 at 15 35 11
Screenshot 2022-07-02 at 15 29 08

Thanks!

customFields API calls missing?

I'm just starting out with this library and trying to find the values for some custom fields (as I'm getting an error that I can't create an issue unless I fill out some of these custom fields).

Looking at the docs there are API calls for custom fields, however I can't find all of them in the library.

Am I looking in the wrong spot? I had a quick look through the code and found calls for /rest/api/2/customField/<id>/option but I can't see those calls listed in the JIRA API docs (only /rest/api/2/customFieldOption) so I'm not sure whether the API has changed or if I'm just looking in the wrong place! I was wanting to make a GET to /rest/api/2/customFields but can't find where that one is implemented.

Would you mind pointing me in the right direction for the custom field calls? Thanks!

Bulk fetch user api's do not work as expected.

Hey @MrRefactoring,

Awesome library. I found an issue with bulk fetching users. Are there any other methods to use when fetching users by username?

These are the 2 api's where the method in jira.js (bulkGetUsersMigration) seems to be buggy and passes all users in one username parameter:

https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-users/#api-rest-api-3-user-bulk-migration-get
https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-users/#api-rest-api-2-user-bulk-migration-get

Thanks for your work!
Max

parameter docs returning 404s

Hi,

I was trying to find out how to provide the parameters to functions that require both a path parameter and some body parameters, linke jira.issueWatchers.addWatcher().

The readme/docs point to https://mrrefactoring.github.io/jira.js/#decreasing-webpack-bundle-size. This has a list of links on the right side of the page, most of which return a 404 directly or after clicking through to the models/parameters.

i.e.
version2/parameters/addWatcher points to https://mrrefactoring.github.io/jira.js/modules/version2_parameters_addWatcher.html which returns a 404.

agile/issue points to https://mrrefactoring.github.io/jira.js/modules/agile_issue.html which points to https://mrrefactoring.github.io/jira.js/classes/agile_issue.Issue.html which returns a 404.

Or am I missing something and should I look for the paramater specs somewhere else?

As stated I am looking to add a watcher to an issue.

Valentijn

adding an attachment

Hi,

sorry to brother you, however, I have an issue in using your new addAttachment method.

In my render process I run the following:

import { HttpClient } from '@angular/common/http';

  constructor(
    private http: HttpClient
  ) {}

uploadMyAttachment {
var issueID = 'issueID-450';
let fileData = this.http.get("C://somepicture.png", { responseType: 'text' as 'json'});
let fileName = 'problem.base.dokument.download';

this.jira.issueAttachments.addAttachment({
      issueIdOrKey: issueID,
      attachment: AddAttachment.Attachment ({
        filename: fileName,
        file: fileData
    })
    })    
                    .then((currentIssue) => {
                      return currentIssue;
                    })
                    .catch((err) => {
                      this.logError(err);
                      this.handleError(err);
                    });
}

It compiles fine, but at runtime I get this error:
add attachment for CQSSPIEL-450
zone-mix.js:3298 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Attachment' of undefined
TypeError: Cannot read property 'Attachment' of undefined

Include responseText in error message.

Currently on XSRF errors, the error message only says "Request failed with status code 403", and the details "XSRF check failed" are only available as error.response.data. It might be a good idea to include that in the actual error message.

Configure the underlying HTTP Client

Hi,

I have some trouble getting jira.js to work on the staging/prod machine, as I am only getting back

Error: socket hang up
     at createHangUpError (_http_client.js:332:15)
     at Socket.socketOnEnd (_http_client.js:435:23)
     at Socket.emit (events.js:203:15)
     at endReadableNT (_stream_readable.js:1145:12)
     at process._tickCallback (internal/process/next_tick.js:63:19)

when trying to load a filter with

const filter = await client.filters.getFilter({
			id: '123456',
		})

Its working from my development machine, so I suppose it is somehow related to proxy settings or similar.

How can I configure the underlying HTTP Client to ignore proxy? Is there a way to do this?

Even printing the complete error why it immediately hangs up does not really help me. The only hint I saw is this:

_options:
       { maxRedirects: 21,
         maxBodyLength: 10485760,
         protocol: 'http:',
         path:
          'https://jiraserv/rest/api/2/filter/67119',
         method: 'GET',
         headers: [Object],
         agent: undefined,
         agents: [Object],
         auth: undefined,
         hostname: 'proxy.host.net',
         port: '3128',
         beforeRedirect: [Function: beforeRedirect],
         nativeProtocols: [Object],
         pathname:
         'https://jiraserv/rest/api/2/filter/67119' },

which results in

_currentUrl:
      'http://proxy.host.net:3128/https://jiraserv/rest/api/2/filter/67119' },

which does not look ok.

Webhook : enable event

Dear @MrRefactoring

What about webhook from Jira service desk and Jira.

The idea is to get event each time a webhook is trigged by Jira service desk also for Jira

Best regards

"ReferenceError: URL is not defined" when OAuth 1.0 is in use

Environment:
Node v8.17.0 & MeteorJS v1.8.1

Brief situation:
When using OAuth to construct a client (in my case I'm accessing Jira server, instead of Jira cloud) and use it to call any APIs, "ReferenceError: URL is not defined" got thrown.
As a side note OAuth2 connection toward Jira cloud works out of the box.

Steps to reproduce:

  1. Use OAuth to construct either a Version2Client or Version3Client (Jira Server is used for my case )
  2. Make any API calls
  3. "ReferenceError: URL is not defined" will be thrown.

Possible fix:
As suggested by the error message, the URL package is not being imported in /out/services/authenticationService/authentications/createOAuthAuthenticationToken.js. (I'm not sure if it's imported by default in newer Node versions)
Adding const URL = require("url").URL in the file will fix the issue.

p.s. Thanks for the package btw. It saves tons of time constructing raw HTTP requests :)

401 with `basic` authentication using email & apiToken

Using the token authorization, e.g.

import { Version2Client } from 'jira.js';

const client = new Version2Client({
  host: 'https://your-domain.atlassian.net',
  authentication: {
    basic: {
      email: '[email protected]',
      apiToken: 'YOUR_API_TOKEN',
    },
  },
});

I'm getting an error that starts off:

(node:74821) UnhandledPromiseRejectionWarning: Error: Request failed with status code 401

and then indicates the problem is at createError in node_modules/axios/lib/core/createError.js:16:15.

After a lot of debugging (including https://github.com/Gerhut/axios-debug-log and putting https://www.npmjs.com/package/axios#handling-errors in node_modules/jira.js/out/clients/baseClient.js at the end of line 62), it appears that Atlassian is responding with:

'Basic authentication with passwords is deprecated.  For more information, see: https://developer.atlassian.com/cloud/confluence/deprecation-notice-basic-auth/\n'

But I definitely don't have a password anywhere in site (๐Ÿฅ).

I'm going to keep digging, but (a) if anyone else is running into this, there's already an issue open, so hopefully they don't have to go through quite the rigamarole that I have (but, please feel free to add any addition details) and (b) I'm hoping that with this information @MrRefactoring might be able to debug it and fix it faster than I can. ๐Ÿคž

CORS issue with all APIs

@MrRefactoring Thanks for your great work on this.
Sorry this might be a dumb question as this CORS issue happens to me.

Screen Shot 2020-09-22 at 11 38 16 am

Could you please help me? Or is there a way to bypass this?

FYI, I do test my apiToken and it works fine in Postman.

Unable to pass specific account ID when adding Watcher to Issue

The only functionality in jira.js to add a watcher to an issue is by using the current user. Their API does however offer the functionality to pass along an optional accountID to assign someone else as watched based on their Jira ID. This is a crucial functionality for my usage as our API needs to assigns specific users to issues rather than the currently authenticated one.

`issueComments.updateComment` attaches `string` body, causing 405

The method issueComments.updateComment only forwards the parameters.body part of the data to the request (even if there are more properties that can be updated.)

When this reaches Axios, its parser sees the data is not an object and thus formats it as form-data and send the request onto Jira. This causes a 405 as JIRA expects application/json.

    const config: RequestConfig = {
      url: `/rest/api/2/issue/${parameters.issueIdOrKey}/comment/${parameters.id}`,
      method: 'PUT',
      params: {
        expand: parameters.expand,
      },
      data: parameters.body, // <-- {data: "string"} as opposed to {data: {body: "string"}}
    };

That is an easy fix, will try to send a PR for this. It affects v2 and v3.

There is however a follow up issue (not for my use case but as per docs) that this endpoint allows: visibility, properties and "anything else" (API Docs) so all those are currently not supported.

Unable to transition a bug

First of all thank you for this API. Though I have been implementing this API in my framework where I want to transition the state of the bug.
updateIssue(){ const opts = { issueIdOrKey: xxx, update: { comment: [ { add: { body: 'Test automated comment', }, }, ], transition: { id: 'xxxx' } } await client.issues.transitionIssue(opts) }

I am unable to transit the issue to the desired state and even I am unable to update comment to the bug. Though if I use
issue.editIssue(opts) I am able to update comment to the issue but still unable to transit the issue.

Bug with IssueBean typings

Hi, I am reading the status from an issue:

static getStatus = (i: IssueBean): string => {
    return (i as any).fields.status.name;
}

If I cast the issue to "any" it work, otherwise I get a compile error because "fields" doesn't have a type definition. Is there a better way to handle this? Do I need to install the types for the library?

Thanks, really appreciate your work!

Originally posted by @manupiastra in #123

After installation in Angular Project Giving Error

Warning: /home/learner/LearningSpace/uxtool/src/app/dashboard/create-user-stories/create-user-stories.component.ts depends on 'jira.js'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

Error: ./node_modules/windows-release/node_modules/cross-spawn/index.js
Module not found: Error: Can't resolve 'child_process' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/cross-spawn'

Error: ./node_modules/windows-release/node_modules/execa/index.js
Module not found: Error: Can't resolve 'child_process' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/execa'

Error: ./node_modules/atlassian-jwt/dist/lib/jwt.js
Module not found: Error: Can't resolve 'crypto' in '/home/learner/LearningSpace/uxtool/node_modules/atlassian-jwt/dist/lib'

Error: ./node_modules/oauth/lib/oauth2.js
Module not found: Error: Can't resolve 'crypto' in '/home/learner/LearningSpace/uxtool/node_modules/oauth/lib'

Error: ./node_modules/oauth/lib/oauth.js
Module not found: Error: Can't resolve 'crypto' in '/home/learner/LearningSpace/uxtool/node_modules/oauth/lib'

Error: ./node_modules/isexe/mode.js
Module not found: Error: Can't resolve 'fs' in '/home/learner/LearningSpace/uxtool/node_modules/isexe'

Error: ./node_modules/isexe/windows.js
Module not found: Error: Can't resolve 'fs' in '/home/learner/LearningSpace/uxtool/node_modules/isexe'

Error: ./node_modules/isexe/index.js
Module not found: Error: Can't resolve 'fs' in '/home/learner/LearningSpace/uxtool/node_modules/isexe'

Error: ./node_modules/windows-release/node_modules/cross-spawn/lib/util/readShebang.js
Module not found: Error: Can't resolve 'fs' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/cross-spawn/lib/util'

Error: ./node_modules/oauth/lib/oauth2.js
Module not found: Error: Can't resolve 'http' in '/home/learner/LearningSpace/uxtool/node_modules/oauth/lib'

Error: ./node_modules/oauth/lib/oauth.js
Module not found: Error: Can't resolve 'http' in '/home/learner/LearningSpace/uxtool/node_modules/oauth/lib'

Error: ./node_modules/oauth/lib/oauth2.js
Module not found: Error: Can't resolve 'https' in '/home/learner/LearningSpace/uxtool/node_modules/oauth/lib'

Error: ./node_modules/oauth/lib/oauth.js
Module not found: Error: Can't resolve 'https' in '/home/learner/LearningSpace/uxtool/node_modules/oauth/lib'

Error: ./node_modules/human-signals/build/src/main.js
Module not found: Error: Can't resolve 'os' in '/home/learner/LearningSpace/uxtool/node_modules/human-signals/build/src'

Error: ./node_modules/human-signals/build/src/signals.js
Module not found: Error: Can't resolve 'os' in '/home/learner/LearningSpace/uxtool/node_modules/human-signals/build/src'

Error: ./node_modules/macos-release/index.js
Module not found: Error: Can't resolve 'os' in '/home/learner/LearningSpace/uxtool/node_modules/macos-release'

Error: ./node_modules/os-name/index.js
Module not found: Error: Can't resolve 'os' in '/home/learner/LearningSpace/uxtool/node_modules/os-name'

Error: ./node_modules/windows-release/index.js
Module not found: Error: Can't resolve 'os' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release'

Error: ./node_modules/windows-release/node_modules/execa/lib/kill.js
Module not found: Error: Can't resolve 'os' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/execa/lib'

Error: ./node_modules/windows-release/node_modules/cross-spawn/lib/parse.js
Module not found: Error: Can't resolve 'path' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/cross-spawn/lib'

Error: ./node_modules/windows-release/node_modules/cross-spawn/lib/util/resolveCommand.js
Module not found: Error: Can't resolve 'path' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/cross-spawn/lib/util'

Error: ./node_modules/windows-release/node_modules/execa/index.js
Module not found: Error: Can't resolve 'path' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/execa'

Error: ./node_modules/windows-release/node_modules/npm-run-path/index.js
Module not found: Error: Can't resolve 'path' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/npm-run-path'

Error: ./node_modules/windows-release/node_modules/which/which.js
Module not found: Error: Can't resolve 'path' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/which'

Error: ./node_modules/merge-stream/index.js
Module not found: Error: Can't resolve 'stream' in '/home/learner/LearningSpace/uxtool/node_modules/merge-stream'

Error: ./node_modules/windows-release/node_modules/get-stream/buffer-stream.js
Module not found: Error: Can't resolve 'stream' in '/home/learner/LearningSpace/uxtool/node_modules/windows-release/node_modules/get-stream'

My Package.json

{
"name": "uxtool",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~11.0.4",
"@angular/cdk": "^11.2.3",
"@angular/common": "~11.0.4",
"@angular/compiler": "~11.0.4",
"@angular/core": "~11.0.4",
"@angular/forms": "~11.0.4",
"@angular/material": "^11.2.3",
"@angular/platform-browser": "~11.0.4",
"@angular/platform-browser-dynamic": "~11.0.4",
"@angular/router": "~11.0.4",
"@dabeng/ng-orgchart": "^1.0.2",
"bootstrap": "^5.0.2",
"jira.js": "^2.5.2",
"node": "^10.0.0",
"nodejs": "^0.0.0",
"orgchart": "^3.1.1",
"rxjs": "~6.6.0",
"tslib": "^2.0.0",
"uuid": "^8.3.1",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.1100.4",
"@angular/cli": "~11.0.4",
"@angular/compiler-cli": "~11.0.4",
"@types/jasmine": "~3.6.0",
"@types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~5.1.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2"
}
}

415 'Unsupported Media Type' when POSTing

While trying to use the REST API to vote on an issue, I got the 415 'Unsupported Media Type' error. The API seems to expect that these requests body are in application/json format, but the requests are instead being sent as application/x-www-form-urlencoded.

Could this be a change from the API or am I missing some config? Other POST calls seem to also expect JSON. Adding the following line to the request config fixes the problem:

https://github.com/lopis/jira.js/blob/master/src/version3/issueVotes.ts#L85

Problems with getIssue()->fields->fixVersions

Hi,

I've recently started to use jira.js to perform an integration against a Jira Server (not Cloud). Everything seems to be working great but today have faced a problem with getIssue()->fixVersions.

It's defined as string[] and here (again, against Jira Server, not Jira Cloud), I'm getting structures like:

[
  {
    self: 'https://example.com/rest/api/2/version/11111',
    id: '14852',
    description: 'xxxxx,
    name: '2.8.7',
    archived: true,
    released: true,
    releaseDate: 'yyyy-mm-dd'
  },
  {
    self: 'https://example.com/rest/api/2/version/11112',
    id: '14853',
    description: 'xxxxx',
    name: '2.9.1',
    archived: true,
    released: true,
    releaseDate: 'yyy-mm-dd'
  }
]

Obviously, that avoids any operation to be performed with typescript on that element. Note that I'm a complete js/ts newbie (this is my very first attempt to build something with it). And also, I've not been able to verify what's returned against a Jira Cloud instance (although it would surprise me that they are so different at that point, AFAIK they are 99% the same).

So, sorry if the reported issue is wrong, but that's what I've detected and thought that reporting it was the way to go.

CIao :-)

In the IssueTransition interface the `to` field is incorrect

When querying from Jira and looking at the IssueTransition object returned, the to value is a StatusDetails object, not an array of StatusDetails[] objects.

Selected transition:{
        "id": "151",
        "name": "Blocked",
        "to": {
            "self": "https://xxxx.atlassian.net/rest/api/2/status/10200",
            "description": "",
            "iconUrl": "https://xxxx.atlassian.net/images/icons/statuses/generic.png",
            "name": "Blocked",
            "id": "10200",
            "statusCategory": {
                "self": "https://xxxx.atlassian.net/rest/api/2/statuscategory/2",
                "id": 2,
                "key": "new",
                "colorName": "blue-gray",
                "name": "To Do"
            }
        },
        "hasScreen": false,
        "isGlobal": true,
        "isInitial": false,
        "isAvailable": true,
        "isConditional": false,
        "isLooped": false
    }

to?: StatusDetails[];

This also applies in both version2 and version3.

URLs for Agile endpoint request configs missing "/rest" prefix

Hi,

Thanks for a great library!

I just started using the Agile client to fetch board details and found that I was getting 404s, despite the Version2 client working just fine.

I noticed that in the error logs, the path used in a failing example to get a board's configuration was:

  • <my-domain>/agile/1.0/board/15/configuration

However, the path should be:

  • <my-domain>/rest/agile/1.0/board/15/configuration (note the /rest prefix).

A simple workaround is to manually add this prefix to the config:

const client = new AgileClient({
  host: `${host}/rest`,
  authentication: // ...
}

However, I assume this isn't intended? Or is this something which varies across different versions of Jira? I'm using Jira cloud, for reference.

If this is something which should be fixed then I'd be happy to submit a PR if helpful.

Problem with Version2Client

Hello,
I have a problem with this class. Maybe it's my fault because i don"t know how to use or install it ^^
This is my error message : (btw my node version is 16.14.0 and the version of jira.js is 2.11.0)
image

And there my code who does not compile :

import { Version2Client } from 'jira.js';

async function getIssue(client: Version2Client, issueKey: string): Promise<any> {
    const param = {
        issueIdOrKey: issueKey,
    };
    const issue = await client.issues.getIssue(param);
    console.log(issue);
    return issue;
}

function login(email: string, apiToken: string): Version2Client {
    const client = new Version2Client({
        host: 'https://my-domain.atlassian.net',
        authentication: {
            basic: {
                email: email,
                apiToken: apiToken,
            },
        },
    });
    return client;
}

export { getIssue, login };

ReferenceError: Buffer is not defined

Hi,

I like to use jira.js and have addit it to my project. However, I run into problems when I try to login to jira, by getting the below buffer error:

error userlogin ReferenceError: Buffer is not defined
at Object.getAuthentication (index.js:35)
at Client. (index.js:172)
at step (index.js:55)
at Object.next (index.js:36)
at index.js:30
at new ZoneAwarePromise (zone-mix.js:913)
at push.32ji.__awaiter (index.js:26)
at Client.sendRequest (index.js:166)
at Myself. (myself.js:151)
at step (myself.js:44)

I setup my conection like this:

const jira = new Client({
  host: host,
  authentication: {
    basic: {
      username: username,
      password: password
    }
  }
});

return jira.myself.getCurrentUser()
.then((user) => {
   console.log('userlogin',user);
  return user;
})
.catch((err) => {
  console.log('error userlogin',err);
  this.logError(err);
  return err;
}); 

The issue seems to be in node_modules\jira.js\out\helpers\index.js where the buffer cannot be used:
return "Basic " + Buffer.from(username + ":" + (apiToken || password)).toString('base64');

Any idea what I can do?
Without success I tried inside polyfills.ts:
(window as any)['global'] = window;
global.Buffer = global.Buffer || require('buffer').Buffer;

thx

"TypeError: errorHandler is not a function" after migrating from jira-connector

I'm working in a project that had jira-connector module. I've changed that and did the several changes to work with jira.js, but an error is raised when I execute the script.

Path_To_Project\node_modules\jira.js\out\clients\baseClient.js:84
                return errorHandler(err);
                       ^

TypeError: errorHandler is not a function
    at Version2Client.<anonymous> (Path_To_Project\node_modules\jira.js\out\clients\baseClient.js:84:24)
    at Generator.next (<anonymous>)
    at fulfilled (Path_To_Project\node_modules\jira.js\node_modules\tslib\tslib.js:115:62)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

This is my setup for client:

var JiraClient2 = require('jira.js')
var jiraQualirede = new JiraClient2.Version2Client({
  host: 'HOST_HERE',
  authentication: {
    basic: {
      username: 'USER_HERE',
      password: 'PASSWORD_HERE',
    },
  },
  newErrorHandling: true
  
});

Browser not supported

requiring the package in a vanila JS environment in the browser I get the following error:

Uncaught Error: Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.
    at Object.get (browser-external:stream:3)
    at node_modules/node-fetch/lib/index.mjs (index.mjs:11)
    at __init (jira_js.js?v=2347c18f:33)
    at node_modules/telemetry.jira.js/out/services/apiClient.js (apiClient.js:13)
    at __require2 (jira_js.js?v=2347c18f:36)
    at node_modules/telemetry.jira.js/out/services/index.js (index.js:13)
    at __require2 (jira_js.js?v=2347c18f:36)
    at node_modules/telemetry.jira.js/out/telemetryClient.js (telemetryClient.js:13)
    at __require2 (jira_js.js?v=2347c18f:36)
    at node_modules/telemetry.jira.js/out/index.js (index.js:16)

unfortunately this also happens with telemetry: false

TS bug with Create Issue model

There appears to be a bug with createIssue. I use the following code:

const issue = {
      fields: {
        summary: title,
        issuetype: {
          id: issuetype_id,
        },
        project: {
          id: project_id,
        },
        description: {
          type: 'doc',
          version: 1,
          content: [
            {
              type: 'paragraph',
              content: [
                {
                  text: description,
                  type: 'text',
                },
              ],
            },
          ],
        },
      },
    }

    client.issues.createIssue(issue)

Which is correct based on the API Documentation: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issues/#api-rest-api-3-issue-post

However this error shows in typescript:

Types of property 'content' are incompatible.
          Type '{ type: string; content: { text: string; type: string; }[]; }[]' is not assignable to type '{ type: string; text: string; content?: any; }[]'.
            Property 'text' is missing in type '{ type: string; content: { text: string; type: string; }[]; }' but required in type '{ type: string; text: string; content?: any; }'.ts(2345)

If I conform to the error shown, the client returns an error: We can't create this issue for you right now, it could be due to unsupported content you've entered into one or more of the issue fields. If this situation persists, contact your administrator as they'll be able to access more specific information in the log file.. However, if I instead use client.issues.createIssue(issue as any) to get around the compiler error everything works as expected.

support personal access tokens for JIRA Server authentication

Is your feature request related to a problem? Please describe.
In JIRA Server 8.14 and Confluence Server 7.9 atlassian has (finally) added tokens as a way to authenticate to the REST API. Much better then people using their company wide ldap password for this (and storing it in places).

Describe the solution you'd like
I think we should support this new authentication method as JIRA Datacenter will also use it and stay beyond 2024. And basic authentication with passwords will be deprecated by atlassian.

Describe alternatives you've considered
Add support for https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html

Additional context
Please note these personal access tokens are slightly different from the JIRA Cloud api tokens (thank you atlassian).

Cloud: curl -H "Authorization: Basic <base64(<username>:<yourToken>>)" https://{jiraBaseUrl}/rest/api/

Server: curl -H "Authorization: Bearer <yourToken>" https://{jiraBaseUrl}/rest/api/

change content type for attachment upload

Hi,

I like to upload an attachment, but get an 415 error. While adding an item I need the content-type 'application/json', however, this changes for an upload to 'multipart/form-data'. Therefore I tried this, but has no effect:

this.jira.issueAttachments.addAttachment({
issueIdOrKey: issue.id,
jiraSettings: {
host: 'https://to.my.jira',
baseRequestConfig: {
headers: {
'X-Atlassian-Token': 'nocheck',
'Content-Type': 'multipart/form-data'
},
},
},
key: attachements[1]
}

newErrorHandling Deprecation Warning Without Explanation

I keep getting "Deprecation warning: New error handling mechanism added. Please use newErrorHandling: true in config" output.

I would love to "upgrade" to the new error handling, but I have no idea what it is or how it is used. I cannot find the usage in your code or documentation. I just see it being set in configs, including the tests.

Why the deprecation warning when we don't know what it does or how to support?

Disable telemetry by default

Hello,

Thanks for a great library! But I think it makes sense to have telemetry disabled by default to avoid violating user privacy. I don't know any client libraries that introduce such a side effect, and I would expect many people won't know about it either until it's too late.

Issue transitions/getIssue returning 404 with issueKey

I tried to get the available transition for a specific issue with issueKey. if I try with issueId its works fine (i.e 10034 etc). but if I try with issueKEY (TEST-123) it returns 404.

Also, I checked the issue transitions API in postman it's working fine.

const config = new Version2Client({
              host: hostUrl,
              authentication: {
                  basic: {
                      email: emailAddress,
                      apiToken: apiToken
                  }
              }
            });

// facing issue with this 
  config.issues.getTransitions({issueIdOrKey: 'TEST-345'}).then(response => {
         console.log(response)
         }).catch(response => {
        console.log("err", response);
       })

     // it's working fine with issueID 
    config.issues.getTransitions({issueIdOrKey: 1203}).then(response => {
         console.log(response)
         }).catch(response => {
        console.log("err", response);
       })
     

Enable Experimental APIs in ServiceDeskClient

When attempting to query an experimental endpoint, the following error is displayed:
API is experimental. Experimental APIs are not guaranteed to be stable within the preview period. You must set the header 'X-ExperimentalApi: opt-in' to opt into using this API.

equest failed with status code 403 XSRF check failed

I have sucessfully opened a jira connection, I can read project version and now I like to add a new issue:

this.jira.issues.createIssue({
      'fields': {
        'project': {
          'key': 'testjira'
        },
        'summary': 'a single ticket',
        'description': 'a simple text',
        'issuetype': {'id': 1}
      }
    })
                    .then((currentIssue) => {
                      return currentIssue;
                    })
                    .catch((err) => {
                      this.logError(err);
                      this.handleError(err);
                    });

This creates an error: An error occured Error: Request failed with status code 403 XSRF check failed

A google search mentions that this is a problem of the User-Agent. I have tried to change it:

this.jira = new Client({
      host: host,
      baseRequestConfig: {
        headers: {
          'Content-Type': 'application/json',
          'User-Agent': 'dumy agent'
        }},
      authentication: {
        basic: {
          username: username,
          password: password
        }
      }
    });

However, this creates another error: Refused to set unsafe header "User-Agent"

Why can I read Jira, but cannot write to it?

Receiving 404 error with certain functions

For some reason some functions always return 404 errors. To be more specific, a situation where this is present is with getting project details. I have no issues getting the information from the getAllProjects() function, however when I use the getProject(<project_id>) the error is present.

Furthermore, when I try to retrieve the data with Postman and the regular api url (https://your-domain.atlassian.com/rest/api/3/project/{projectIdOrKey}) I have no issues.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.