Skip to content

Commit

Permalink
Merge pull request #174 from arjunkomath/replace-request
Browse files Browse the repository at this point in the history
Replace request with axios
  • Loading branch information
arjunkomath authored Sep 25, 2021
2 parents 049b43b + 73fa6c0 commit 8bb726e
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 380 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Run tests

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [10.x, 12.x, 14.x, 15.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Install dependencies
run: npm ci
- run: npm test
- run: npm run coverage
65 changes: 0 additions & 65 deletions .travis.yml

This file was deleted.

2 changes: 1 addition & 1 deletion lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class Freshdesk {
*/
constructor(baseUrl, apiKey) {
this.baseUrl = baseUrl
this._auth = 'Basic ' + new Buffer(`${apiKey}:X`).toString('base64')
this._auth = 'Basic ' + Buffer.from(`${apiKey}:X`, 'utf-8').toString('base64')
}

/**
Expand Down
103 changes: 38 additions & 65 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ http://spdx.org/licenses/MIT

'use strict'

const request = require('request')
const debug = require('debug')('freshdesk-api')
const axios = require('axios')
const debug = require('debug')('freshdesk-api')
const FormData = require('form-data');

/**
* Freshdesk's API protocol violations
Expand All @@ -45,8 +46,8 @@ class FreshdeskError extends Error{

this.data = data

this.status = res.statusCode
this.apiTarget = `${res.request.method} ${res.request.uri.href}`
this.status = res.status
this.apiTarget = `${res.request.method} ${res.request.path}`
this.requestId = res.headers['x-request-id']
}
}
Expand All @@ -56,9 +57,7 @@ function createResponseHandler (cb) {
return function (error, response, body) {
if (error) {
debug('Error on request: [%s], req path [%s] raw body: %o',
error,
response ? response.request.path : undefined,
response ? response.request.body : undefined
error
)
return cb(error)
}
Expand All @@ -69,7 +68,7 @@ function createResponseHandler (cb) {
requestId: '',
}

debug('Got API response, status [%s]', response.statusCode)
debug('Got API response, status [%s]', response.status)

if (response
&& response.headers
Expand All @@ -88,28 +87,13 @@ function createResponseHandler (cb) {
extra.requestId = response.headers['x-request-id']
}

switch(response.statusCode) {
switch(response.status) {
// SUCCESS
// https://httpstatuses.com/200 OK
// https://httpstatuses.com/201 Created
case 200:
case 201:
try {
data = JSON.parse(body)
} catch (err) {
if (err instanceof SyntaxError) {
debug('Valid HTTP status [%s], but not a JSON resp. Path:[%s] raw body: %o',
response.statusCode,
response.request.path,
response.request.body
)
return cb(new FreshdeskError('Not a JSON response from API', body, response))
}

// unknown error
return cb(err)
}
return cb(null, data, extra)
return cb(null, body, extra)

// SUCCESS for DELETE operations
// https://httpstatuses.com/204 No Content
Expand All @@ -136,68 +120,57 @@ function createResponseHandler (cb) {
default:
debug('path:[%s] raw body: %o',
response.request.path,
response.request.body
response.request.data
)

try {
data = JSON.parse(body)
} catch (err) {
if (err instanceof SyntaxError) {
// data is not a JSON, so lets return it "AS IS"
debug('Unexpected HTTP status [%s], and not a JSON resp. Path:[%s] raw body: %o',
response.statusCode,
response.request.path,
response.request.body
)
return cb(new FreshdeskError('Not a JSON response from API', body, response))
}

// unknown error
return cb(err)
}

return cb(new FreshdeskError(data.description, data, response))
return cb(new FreshdeskError(body.description, body, response))
}
}
}

// TODO: try to make less params here
function makeRequest(method, auth, url, qs, data, cb) { // eslint-disable-line max-params
async function makeRequest(method, auth, url, qs, data, cb) { // eslint-disable-line max-params
const options = {
method: method,
headers: {
'Content-Type': 'application/json',
'Authorization': auth
},
url: url, // for debugging set to: "https://httpbin.org/get"
qs: qs
params: qs
}

let formData = false
if (data) {
if ('attachments' in data && Array.isArray(data.attachments)) {
formData = true
options.headers['Content-Type'] = 'multipart/form-data'
var form = new FormData();

for (let i = 0; i < Object.keys(data).length; i++) {
const key = Object.keys(data)[i];
if (Array.isArray(data[key])) {
for (let i = 0; i < data[key].length; i++) {
form.append(key + '[]', data[key][i])
}
} else {
form.append(key, data[key])
}
}

options.headers['Content-Type'] = form.getHeaders()['content-type']
options.data = form
} else {
options.body = JSON.stringify(data)
options.data = JSON.stringify(data)
}
}

if (!formData) {
return request(options, createResponseHandler(cb))
}

// Handle attachments
const r = request(options, createResponseHandler(cb))
const form = r.form();
for (let i = 0; i < Object.keys(data).length; i++) {
const key = Object.keys(data)[i]
if (key === 'attachments') {
for (let i = 0; i < data[key].length; i++) {
form.append('attachments[]', data[key][i])
}
try {
const response = await axios(options);
return createResponseHandler(cb)(null, response, response.data);
} catch (error) {
if (error.response) {
return createResponseHandler(cb)(null, error.response, error.response.data);
} else if (error.request) {
return createResponseHandler(cb)(new Error(error.message), error.request, error.request.data);
} else {
form.append(key, data[key])
return createResponseHandler(cb)(error, error.request, error.request.data);
}
}
}
Expand Down
Loading

0 comments on commit 8bb726e

Please sign in to comment.