Skip to content

Commit

Permalink
Merge pull request #422 from droztech/feat-types
Browse files Browse the repository at this point in the history
feat: tickets & users types + adjustments on types exports + option to throwOriginalException
  • Loading branch information
blakmatrix authored Aug 1, 2024
2 parents 979fed6 + d5b0175 commit 8654236
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 37 deletions.
30 changes: 30 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,36 @@
"types": "./dist/types/index.d.ts",
"default": "./dist/index.js"
}
},
"./clients/*": {
"import": {
"types": "./dist/types/clients/*.d.ts",
"default": "./dist/clients/*.js"
},
"require": {
"types": "./dist/types/clients/*.d.ts",
"default": "./dist/clients/*.js"
}
},
"./clients/*/*": {
"import": {
"types": "./dist/types/clients/*/*.d.ts",
"default": "./dist/clients/*/*.js"
},
"require": {
"types": "./dist/types/clients/*/*.d.ts",
"default": "./dist/clients/*/*.js"
}
},
"./clients/*/*/*": {
"import": {
"types": "./dist/types/clients/*/*/*.d.ts",
"default": "./dist/clients/*/*/*.js"
},
"require": {
"types": "./dist/types/clients/*/*/*.d.ts",
"default": "./dist/clients/*/*/*.js"
}
}
},
"files": [
Expand Down
53 changes: 18 additions & 35 deletions src/clients/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const {
* @property {string} [asUser] - Optional header for making requests on behalf of a user.
* @property {object} [customHeaders] - Any additional custom headers for the request.
* @property {boolean} [throttle] - Flag to enable throttling of requests.
* @property {boolean} [throwOriginalException] - Throw the original exception when API requests fail.
* @property {CustomEventTarget} eventTarget - Event target to handle custom events.
* @property {Array} sideLoad - Array to handle side-loaded resources.
* @property {Array} jsonAPINames - Array to hold names used in the JSON API.
Expand Down Expand Up @@ -166,11 +167,7 @@ class Client {
!Array.isArray(args.at(-1)) &&
args.pop();

try {
return await this.transporter.request(method, uri, body);
} catch (error) {
throw new Error(`Raw request failed: ${error.message}`);
}
return this.transporter.request(method, uri, body);
}

/**
Expand All @@ -197,6 +194,10 @@ class Client {
);
return {response, result: responseBody};
} catch (error) {
if (this.options.throwOriginalException) {
throw error;
}

const {
message,
result: {error: {title = '', message: errorMessage = ''} = {}} = {},
Expand Down Expand Up @@ -244,43 +245,25 @@ class Client {

const fetchPagesRecursively = async (pageUri) => {
const isIncremental = pageUri.includes('incremental');

try {
const responseData = await __request.call(
this,
method,
pageUri,
...args,
);
const nextPage = processPage(responseData);
if (
nextPage &&
(!isIncremental ||
(responseData.response && responseData.response.count >= 1000))
) {
return fetchPagesRecursively(nextPage);
}
} catch (error) {
throw new Error(`Request all failed during fetching: ${error.message}`);
const responseData = await __request.call(this, method, pageUri, ...args);
const nextPage = processPage(responseData);
if (
nextPage &&
(!isIncremental ||
(responseData.response && responseData.response.count >= 1000))
) {
return fetchPagesRecursively(nextPage);
}
};

try {
await fetchPagesRecursively(uri);
return flatten(bodyList);
} catch (error) {
throw new Error(`RequestAll processing failed: ${error.message}`);
}
await fetchPagesRecursively(uri);
return flatten(bodyList);
}

// Request method for uploading files
async requestUpload(uri, file) {
try {
const {response, result} = await this.transporter.upload(uri, file);
return checkRequestResponse(response, result);
} catch (error) {
throw new Error(`Upload failed: ${error.message}`);
}
const {response, result} = await this.transporter.upload(uri, file);
return checkRequestResponse(response, result);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/clients/core/tickets.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ class Tickets extends Client {
* Update an existing ticket by its ID.
* @param {number} ticketId - The ID of the ticket to update.
* @param {CreateOrUpdateTicket} ticket - The updated ticket data as an object.
* @returns {Promise<{result: Ticket}>} A promise that resolves to the updated ticket object.
* @returns {Promise<{result: Ticket, response: {ticket:Ticket, audit:any[]}}>} A promise that resolves to the updated ticket object.
* @async
* @throws {Error} If `ticketId` is not a number or if `ticket` is not an object.
* @see {@link https://developer.zendesk.com/api-reference/ticketing/tickets/tickets/#update-ticket}
Expand Down
2 changes: 1 addition & 1 deletion src/clients/core/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class Users extends Client {
/**
* Shows details of a user by ID.
* @param {number} id - The ID of the user.
* @returns {Promise<User>} The user's details.
* @returns {Promise<{result: User}>} The user's details.
* @async
* @see {@link https://developer.zendesk.com/api-reference/ticketing/users/users/#show-user}
* @example
Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const {ZendeskClientVoice} = require('./clients/voice');
/**
* @typedef {object} ZendeskClientOptions
* @property {string} [token] - Authentication token.
* @property {string} [password] - Authentication password.
* @property {string} [username] - Username for authentication.
* @property {string} [subdomain] - Subdomain for the Zendesk account (e.g., 'mycompany' for 'mycompany.zendesk.com'). If `endpointUri` is provided, this is ignored.
* @property {string[]} [apiType=['core']] - Type of Zendesk API (e.g., 'core', 'helpcenter'). Determines the sub-client to use.
Expand All @@ -19,6 +20,7 @@ const {ZendeskClientVoice} = require('./clients/voice');
* @property {string} [asUser] - Optional header for requests on behalf of a user.
* @property {object} [customHeaders] - Additional custom headers for the request.
* @property {boolean} [throttle] - Enables request throttling.
* @property {boolean} [throwOriginalException] - Throw the original exception when API requests fail.
* @property {boolean} [debug=false] - Enables or disables debug logging.
* @property {object} [logger=ConsoleLogger] - Logger for logging. Defaults to a basic console logger.
* @property {object} [transportConfig] - Configuration for custom transport.
Expand Down
30 changes: 30 additions & 0 deletions test/exceptionshandling.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import process from 'node:process';
import dotenv from 'dotenv';
import {describe, expect, it} from 'vitest';
import {initializeClient} from './setup.js';

dotenv.config();

const username = process.env.ZENDESK_USERNAME;
const token = process.env.ZENDESK_TOKEN;

describe('Zendesk Exceptions Handling', () => {
it('should throw an error for an invalid subdomain', async () => {
const error = new Error('My Custom Error');
error.details = 'Custom Details';

const client = initializeClient({
username,
token,
subdomain: 'any',
throwOriginalException: true,
transportConfig: {
transportFn() {
throw error;
},
},
});

await expect(() => client.users.me()).rejects.toThrowError(error);
});
});

0 comments on commit 8654236

Please sign in to comment.