Coder Social home page Coder Social logo

node-jira-client's Introduction

JavaScript JIRA API for node.js

A node.js module, which provides an object oriented wrapper for the Jira Rest API.

Documentation Jira Rest API Run tests npm Downloads Install Size dependency Status devDependency Status

Installation

Install with the node package manager npm:

$ npm install jira-client

Examples

Create the JIRA client

// With ES5
var JiraApi = require('jira-client');

// With ES6
import JiraApi from 'jira-client';

// Initialize
var jira = new JiraApi({
  protocol: 'https',
  host: 'jira.somehost.com',
  username: 'username',
  password: 'password',
  apiVersion: '2',
  strictSSL: true
});

Find the status of an issue

// ES5
// We are using an ES5 Polyfill for Promise support. Please note that if you don't explicitly
// apply a catch exceptions will get swallowed. Read up on ES6 Promises for further details.
jira.findIssue(issueNumber)
  .then(function(issue) {
    console.log('Status: ' + issue.fields.status.name);
  })
  .catch(function(err) {
    console.error(err);
  });

// ES6
jira.findIssue(issueNumber)
  .then(issue => {
    console.log(`Status: ${issue.fields.status.name}`);
  })
  .catch(err => {
    console.error(err);
  });

// ES7
async function logIssueName() {
  try {
    const issue = await jira.findIssue(issueNumber);
    console.log(`Status: ${issue.fields.status.name}`);
  } catch (err) {
    console.error(err);
  }
}

Documentation

Can't find what you need in the readme? Check out our documentation here: https://jira-node.github.io/

node-jira-client's People

Contributors

anton-rudeshko avatar attrib avatar cdloh avatar dependabot[bot] avatar devxiaolan avatar dhigginbotham avatar dkokic avatar dschmidlin avatar eduardolundgren avatar gabriel403 avatar greenkeeperio-bot avatar idmitme avatar itoche avatar kanoyugoro avatar lucasvo avatar lucasvo-taulia avatar mtscout6 avatar netfantom-spb avatar okitan avatar peteszym avatar pioug avatar randyho-kk avatar rkt2spc avatar satcheluniverse avatar seth10001 avatar shaunburdick avatar steves avatar tebriel avatar woellchen avatar yasumoto 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-jira-client's Issues

Can't use addWorklog

I'm trying to use the addWorklog method without success. Can anyone help me?

This is my worklog object:

const worklog = {
      "started": "2017-03-31T13:39:13.106+0000",
      "timeSpent": "3h 20m",
      "newEstimate": "1d",
}

And I get this error: "400 - {"errorMessages":["Unrecognized field "newEstimate"...

But when I try it without the newEstimate field I get this error: "400 - {"errorMessages":["Worklog must not be null."],"errors":{"newEstimate":"You must supply a valid new estimate."}}"

Add "dev-status" API

JIRA has an undocumented "dev-status" API that is usual when JIRA is integrated with other tools like Stash (Bitbucket Server). For example:

To get info about branches and pull requests related to an issue:

https://{jiraHost}/rest/dev-status/latest/issue/detail?issueId={jiraIssueNumericId}&applicationType=stash&dataType=pullrequest

To get info about commits related to an issue:

https://{jiraHost}/rest/dev-status/latest/issue/detail?issueId={jiraIssueNumericId}&applicationType=stash&dataType=repository

I can also supply scrubbed example response bodies if desired.

Add override for api version

Hey mang,

we have a jira server we're using, would be nice if I could provide a function or something to override the pathname generated in makeUri because we have
example.com/rest/____
and get 404's when /api/${apiVersion} is in there.

Getting 404 when calling findIssue

I am not sure what I am missing, but the sample code itself breaks, and it always gives 404. The URL it forms is https://<atlassian_host>/rest/api/2/issue/<issue_id>?expand=&fields=&properties=&fieldsByKeys=

I am pretty sure the username/password and issue_id are correct, as the same thing works fine on Python client. Can someone please help me.

TransitionIssue and UpdateIssue is not working due to empty responses is not accepted

Critical Issue
When I was trying to call .transitionIssue() it sends request and receiving 204 StatusCode (it works successfully), but console throwing error:

[TypeError: Cannot read property 'errorMessages' of undefined]

The issue is the way how compiled line 115 https://github.com/jira-node/node-jira-client/blob/master/src/jira.js#L115

response = _context.sent; if (!(Array.isArray(response.errorMessages) && response.errorMessages.length > 0)) { _context.next = 6; break; } throw new Error(response.errorMessages.join(', '));

We have to accept empty response in case 204 Status Code was returned according to https://docs.atlassian.com/jira/REST/latest/#api/2/issue-doTransition
Temporary solution would be just add string before 115 with:
if (!response) return response;

Please help to address proper resolution

Minor issue
As I can see in legacy plugin there was also handling of status codes:
if (response.statusCode === 400) { callback('Problem with the JQL query'); return; } if (response.statusCode !== 200) { callback(response.statusCode + ': Unable to connect to JIRA during search.'); return; }

Could we please add something similar?

Can't set strictSSL to false

Looking at line 22: this.strictSSL = options.strictSSL || true;, strictSSL will always be true:

$ node
> const obj = { strictSSL: false };
undefined
> obj.strictSSL || true;
true

Is there any support for cookies based auth?

Hello there,

First of all, thanks for this great lib :)

Wondering if this lib supports the cookies based auth using jsessionid as described here : https://developer.atlassian.com/jiradev/jira-apis/about-the-jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-cookie-based-authentication?

The point is to get a session id once login the user, and then use the session id for every API call until it expires and ask again for a new session id for the user :

headers: {cookie: JSESSIONID=6E3487971234567896704A9EB4AE501F}

The goal is not to pass any user / pass along within each requests ans thus don't trigger the auth workflow every time.

Thanks :)

Can't get changelog from issue successfuly

If we try to get a issue changelog we get error:

jira.findIssue(issue.key, 'changelog').then(function (result) {

});

The issue is on jira.js file on line 369. The solution is:

{
    key: 'findIssue',
    value: function findIssue(issueNumber, expand, fields, properties, fieldsByKeys) {
      return this.doRequest(this.makeRequestHeader(this.makeUri(JSON.parse(JSON.stringify({
        pathname: '/issue/' + issueNumber,
        query: {
          expand: expand,
          fields: fields || '*all',
          properties: properties,
          fieldsByKeys: fieldsByKeys || false,
        }
      })))));
 }

getUsersIssues JQL Error

I'm using JiraApi.getUsersIssues like so:

jira.getUsersIssues ('@someone', false)

and getting an error:

{"errorMessages":["Error in the JQL Query: Expecting either 'OR' or 'AND' but got 'false'. (line 1, character 65)"],"errors":{}}

In looking at the function in the code, it looks like open is just being concatenated -

key: 'getUsersIssues',
    value: function getUsersIssues(username, open) {
      return this.searchJira('assignee = ' + username.replace('@', '\\u0040') + ' ' + ('AND status in (Open, \'In Progress\', Reopened) "' + open + '"'), {});
    }

It seems like this should affect the included status array instead of just being concatenated.

RequestError: TypeError: Failed to fetch

Simple api call receiving error in fetching results. I can see in the network tab of my chrome browser that the call to components returned a 200. Copy the request URL and paste into another tab and the JSON returns as expected. What could cause the inability to 'fetch' results?

    const jira = new JiraApi({
      protocol: 'https',
      host: '<host>',
      apiVersion: 'latest',
    })

    jira.listComponents('ION')
      .then((components) => {
        alert('in success')
        alert(components)
      })
      .catch((err) => {
        alert(err)
      });

Documentation link not obvious

Not sure if anybody else has missed the documentation badge, but I have a couple times. Does it make sense to call out the documentation in it's own section of the readme?

screen shot 2017-03-29 at 8 25 49 pm

Add Option for Bearer Token Authentication

It would be nice to be able to use a previously retrieved Bearer token. I currently use Atlassian's OAuth client to retrieve and OAuth token using the JWT. I think the easiest way to incorporate that feature is to just modify the Authentication to accept Bearer... or if you are willing to accept JWT and have that create an OAuth token that would be even better.

TypeScript Definition

Can you add TypeScript definitions?

  • create the index.d.ts file
  • add "typings": "./index.d.ts" to package.json

How to configure jira (and client) for oauth?

It's not really the issue with the library, but it's a shame that client lib has an option without a hint how to get to use it.

If anyone can help - please don't hesitate.

Thank you.

cannot create jira client

I follow the documentation and insert my credentials to the required fields but couldn't login.
It throws an error as;

RequestError: Error: tunneling socket could not be established, cause=socket hang up

var JiraApi = require('jira-client');
// Initialize
var jira = new JiraApi({
	protocol: 'https',
	host: '@hostname',
	username: '@username',
	password: '@password',
	apiVersion: '2',
            strictSSL: true
});



jira.findIssue(@issueNumber)
	.then(function(issue) {
		console.log('Status: ' + issue.fields.status.name);
	})
	.catch(function(err) {
		console.error(err);
	});

I'm behind corporate proxy is it the problem? I couldn't even define the problem. It just hangs up. What do you suggest me?

Correct Travis CI build link

https://travis-ci.org/node-jira/node-jira-client should actually be https://travis-ci.org/jira-node/node-jira-client so we can see the proper build status.

Request from behind corporate proxy

I get the following error when using the listProjects function:
Error: connect EHOSTUNREACH (some IP address X)

I have seen this EHOSTUNREACH message before and it was caused by being behind a corporate proxy.
Is there a way of giving in proxy details to fix this (like the --proxy flag from curl)?

Cheers

ssl strict = false

Setting strict to false doesn't work I still get a self-signed error. TLS
Any ideas?

Call for maintainers!

I am wondering if this project is still active, I see PRs not merged for a while and issues with no answer.

How can I bind "this" to the promise?

This below code doesn't work. Anyway to bind the parent "this" inside the Promiss?

if (valid) {
    var jira = jiraClient.logonJira("", this.form.userName, this.form.password)
    jira.getCurrentUser().promise().bind(this).then(
        function(resp) {
            this.$store.commit('setAvator', resp.avatarUrls["48x48"])
            this.$store.commit('setJiraClient', jira)
            this.$router.push({
                name: 'home_index'
            })
        }
    ).catch(
        function(err) {
            if(err.statusCode == 401){
                alert("Username and Password don't match")
            } else {
                alert("Server error" + err)
            }
            this.loading = false
        }
    )
}

How edit a issue to change the duedate value

Hi

Sorry for this question but i don't understand how can i edit the issue.

i try this but the duedate does not change :

 var test = {
    "fields": {
        "duedate": "2016-03-03"
     }
}
jira.updateIssue(req.body.keyIssue, test, function(test, body) {
    res.send(body);
    console.log("azerty");
});

NB: There is a Jira object which is initialized just before this

Thank you in advance :)

How to download project image?

I need to save a project image locally so I can serve it up to the user, however it seems I need to make an authenticated API call to get the image data for project.avatarUrls['32x32'] which might look like https://xxx.atlassian.net/secure/projectavatar?size=small&pid=xxx&avatarId=xxx.

Is this something the library already supports and I'm just missing it?

listComponents return no data.

The old previous version (jira) returns all of the components for a project. This version (jira-client) returns no data.

previous version: https://github.com/steves/node-jira
jira-client: https://github.com/jira-node/node-jira-client (forked from jira)

NODE_HTTP=http showed some differences:
< jira-client
> jira

515c150
<         sockets: {},

---
>         sockets: [Object],
545c180
<      options: { rejectUnauthorized: true, path: null },

---
>      options: { path: null },
554c189
<   href: 'http://<myhost>/jira/rest/api/2/project/<myproject>/components',

---
>   href: 'http://<myhost>/jira/rest/api/2/project/<myproject>/components',
556,558c191,193
< HTTP 14315: sockets <myhost>:80:: 1
< HTTP 14315: outgoing message end.
< HTTP 14315: parserOnHeadersComplete { headers:

---
> HTTP 14324: sockets <myhost>:80:: 1
> HTTP 14324: outgoing message end.
> HTTP 14324: parserOnHeadersComplete { headers:

Thanks,
-Jake

Empty properties string causing Internal Server Error on findIssue API call

On JIRA API v2, passing in an empty properties query string param is causing an Internal Server Error. Removing the param entirely or setting it to a * fixes the issue. url.format takes null or undefined values in the querystring and sets them to an empty string.

Changing the following line:

properties: properties || '',

to

properties: properties || '*',

Correctly formats the querystring and findIssue returns valid json.

oauth_problem=signature_invalid when attempting to authenticate using OAuth

When attempting to authenticate using OAuth, the request seems to fail with the message signature_invalid. The output is:
401 - oauth_problem=signature_invalid&oauth_signature=ivO30fqXNHmgWJw5W8nn1RnG22mLRJSu6GO8Rw%2BLc7EYfbiN9ebpHjj2e6O098djpjCYxmdX%2FgTgdppyLOAad5dfSrepe%2F17BovqUskEtG7T6w0sG93aEvqNHZ5BJMpQm%2FP9aY%2Fb2%2FlLXT1TIKrwkU0q6B35MPlHdQjkqSp1vVbOHj4b%2BNHADrieOKOExWdEBuQgIX4J4gJQHrtIbjovMRo1n7pA5Ax9%2FvgRoOmsFulLpY%2FzrtwSlin5nZUGPCYr8UpHMdLbTMhr3OFoGk5PT6ilLpz%2F0XAT9teQ%2FM3Tzwhu6Goje619xg%2Fri2TxrctxBTgOPrnnQLHinuUEiSuSAg%3D%3D&oauth_signature_base_string=GET%26https%253A%252F%252Ftravis.atlassian.net%252Frest%252Fapi%252Flatest%252Fproject%252FGP%26oauth_consumer_key%253D<redacted>%2526oauth_nonce%253D596298020b7442da89751fb6eacc914f%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1459272339%2526oauth_token%253DEQL3QdfAOgFYH56YrMqycRXB4IdjMy55%2526oauth_version%253D1.0&oauth_signature_method=RSA-SHA1

Incorrect Webhooks API URL

Although this is Atlassian issue, at the moment it is holding me back.

Webhooks is not listed under JIRA official documentation (https://docs.atlassian.com/jira/REST/latest/), it is listed under the webhooks documentation (https://developer.atlassian.com/jiradev/jira-apis/webhooks#Webhooks-re) under the following URL:
<JIRA_URL>/rest/webhooks/1.0/webhook/
which doesnt conform to the default URL defind in 'makeUri' function at line 143:
"pathname: this.base + '/rest/api/' + this.apiVersion + pathName"

getUsersIssues returns JQL error

Error
"400 - {"errorMessages":["Error in the JQL Query: 'true' is a reserved JQL word. You must surround it in quotation marks to use it in a query. (line 1, character 80)"],"errors":{}}"

Code
jira.getUsersIssues('myusername',true)

findIssue properties default?

Hi - I'm having some trouble with the basic findIssue sample provided in the readme and was hoping you could help.

When I run this:

var issueNumber = 'CC-1111';
jira.findIssue(issueNumber)
  .then(issue => {
    console.log(issue);
  })
  .catch(err => {
    console.error(err);
  });

I receive an "500 Internal Service Error" from JIRA. In my experience (based almost entirely on building the same type of library for PowerShell), that's a problem with the request (query string on get or json body on post).

This is the uri returned in err:
https://jira.company.com/rest/api/2/issue/CC-1111?expand=&fields=*all&properties=&fieldsByKeys=false

When I plug that into something like Insomnia or Postman, I get the same 500 error.
However, when I add a '*' to the properties field it works great (in a REST browser).

So, back in Node, when I call findIssue like so (forcing some '*' values) it also works great.

var issueNumber = 'CC-1111';
jira.findIssue(issueNumber,'*','*','*','*')
  .then(issue => {
    console.log(issue);
  })
  .catch(err => {
    console.error(err);
  });

Am I doing something wrong? Does the properties field need a default value? Or perhaps the JIRA version I'm running (7.3.1) is expecting something a little different?

Any advice is greatly appreciated.

Thx!
Bryan

Error on getting all boards

Hello,

I have an error on getAllBoards() method.

This is my code :

        jira.getAllBoards()
            .then((jiraOutput) => {
                ......
            })
            .catch(reject);

The error is :

.../node_modules/bluebird/js/release/debuggability.js:868 Unhandled rejection StatusCodeError: 400 - {"errorMessages":["No project could be found with key ''."],"errors":{}}

I found the problem in node-jira-client, it's on getAllBoards method. When there is no projectKeyOrId in argument, param is passed in query string as empty. So Jira try to filter on an empty project name :

return this.doRequest(this.makeRequestHeader(this.makeAgileUri({
        pathname: '/board',
        query: {
          startAt: startAt,
          maxResults: maxResults,
          type: type,
          name: name,
          projectKeyOrId: projectKeyOrId
        }
})));

In the case where I really want to get all board (whithout filtering on project key), I need to remove projectKeyOrId key in query object. And it works.

The "request" library is not installed automatically anymore

Hello!

Thank you for this great library!

However, when trying to use it I get the following error:

###
### The "request" library is not installed automatically anymore.
### But required by "request-promise".
###
### npm install request --save
###

./node_modules/request-promise/lib/rp.js:23
    throw err;
    ^

Error: Cannot find module 'request'
...

You should add the request dependency to this module's package.json file, because request-promise is not enough theses days.

Thanks!

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.