Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(zendesk): remove endpoint global variable #1746

Merged
merged 17 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/v0/destinations/zendesk/config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
const { getMappingConfig } = require("../../util");

const getBaseEndpoint = domain => {
return `https://${domain}.zendesk.com/api/v2/`;
};

const ConfigCategory = {
IDENTIFY: {
name: "ZDIdentifyConfig",
Expand Down Expand Up @@ -44,10 +48,6 @@ const ZENDESK_MARKET_PLACE_NAME = "RudderStack";
const ZENDESK_MARKET_PLACE_ORG_ID = "3339";
const ZENDESK_MARKET_PLACE_APP_ID = "263241";

const getBaseEndpoint = domain => {
return `https://${domain}.zendesk.com/api/v2/`;
};

module.exports = {
getBaseEndpoint,
ConfigCategory,
Expand Down
100 changes: 61 additions & 39 deletions src/v0/destinations/zendesk/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ const logger = require("../../../logger");
const { httpGET } = require("../../../adapters/network");
const {
NetworkInstrumentationError,
InstrumentationError
InstrumentationError,
NetworkError
} = require("../../util/errorTypes");
const { getDynamicErrorType } = require("../../../adapters/utils/networkUtils");
const tags = require("../../util/tags");

function responseBuilder(message, headers, payload, endpoint) {
const response = defaultRequestConfig();
Expand Down Expand Up @@ -280,7 +283,7 @@ async function getUserId(message, headers, baseEndpoint, type) {
return undefined;
}

const zendeskUserId = resp.data.users[0].id;
const zendeskUserId = resp?.data?.users?.[0]?.id;
return zendeskUserId;
} catch (error) {
// logger.debug(
Expand All @@ -294,13 +297,16 @@ async function getUserId(message, headers, baseEndpoint, type) {
async function isUserAlreadyAssociated(userId, orgId, headers, baseEndpoint) {
const url = `${baseEndpoint}/users/${userId}/organization_memberships.json`;
const config = { headers };
const response = await axios.get(url, config);
if (
response.data &&
response.data.organization_memberships.length > 0 &&
response.data.organization_memberships[0].organization_id === orgId
) {
return true;
try {
const response = await axios.get(url, config);
if (
response?.data?.organization_memberships?.[0]?.organization_id === orgId
) {
return true;
}
} catch (error) {
logger.debug("Error :");
sanpj2292 marked this conversation as resolved.
Show resolved Hide resolved
logger.debug(error?.response?.data || error);
}
return false;
}
Expand Down Expand Up @@ -336,8 +342,8 @@ async function createUser(
throw new NetworkInstrumentationError("user not found");
}

const userID = resp.data.user.id;
const userEmail = resp.data.user.email;
const userID = resp?.data?.user?.id;
const userEmail = resp?.data?.user.email;
return { zendeskUserId: userID, email: userEmail };
} catch (error) {
logger.debug(error);
Expand Down Expand Up @@ -435,7 +441,7 @@ async function createOrganization(
return undefined;
}

const orgId = resp.data.organization.id;
const orgId = resp?.data?.organization?.id;
return orgId;
} catch (error) {
logger.debug(`Couldn't create Organization: ${message.traits.name}`);
Expand Down Expand Up @@ -512,15 +518,11 @@ async function processIdentify(
try {
const config = { headers };
const response = await axios.get(membershipUrl, config);
if (
response.data &&
response.data.organization_memberships &&
response.data.organization_memberships.length > 0
) {
if (response?.data?.organization_memberships?.length > 0) {
if (
orgId === response.data.organization_memberships[0].organization_id
orgId === response.data.organization_memberships[0]?.organization_id
) {
const membershipId = response.data.organization_memberships[0].id;
const membershipId = response.data.organization_memberships[0]?.id;
const deleteResponse = defaultRequestConfig();

deleteResponse.endpoint = `${baseEndpoint}users/${userId}/organization_memberships/${membershipId}.json`;
Expand Down Expand Up @@ -557,26 +559,40 @@ async function processTrack(message, destinationConfig, headers, baseEndpoint) {
}
let zendeskUserID;

let url = `${baseEndpoint}users/search.json?query=${userEmail}`;
const url = `${baseEndpoint}users/search.json?query=${userEmail}`;
const config = { headers };
const userResponse = await axios.get(url, config);
if (!get(userResponse, "data.users.0.id") || userResponse.data.count === 0) {
const { zendeskUserId, email } = await createUser(
message,
headers,
destinationConfig,
baseEndpoint
);
if (!zendeskUserId) {
throw new NetworkInstrumentationError("User not found");
}
if (!email) {
throw new NetworkInstrumentationError("User email not found", 400);
try {
const userResponse = await axios.get(url, config);
if (
!get(userResponse, "data.users.0.id") ||
userResponse.data.count === 0
) {
const { zendeskUserId, email } = await createUser(
message,
headers,
destinationConfig,
baseEndpoint
);
if (!zendeskUserId) {
throw new NetworkInstrumentationError("User not found");
}
if (!email) {
throw new NetworkInstrumentationError("User email not found", 400);
}
zendeskUserID = zendeskUserId;
userEmail = email;
}
zendeskUserID = zendeskUserId;
userEmail = email;
zendeskUserID = zendeskUserID || userResponse?.data?.users?.[0]?.id;
} catch (error) {
throw new NetworkError(
sanpj2292 marked this conversation as resolved.
Show resolved Hide resolved
`Failed to fetch user with email: ${userEmail} due to ${error.message}`,
error.status,
{
[tags.TAG_NAMES.ERROR_TYPE]: getDynamicErrorType(error.status)
},
error?.response?.data || error?.response || error
);
}
zendeskUserID = zendeskUserID || userResponse.data.users[0].id;

const eventObject = {};
eventObject.description = message.event;
Expand All @@ -590,9 +606,14 @@ async function processTrack(message, destinationConfig, headers, baseEndpoint) {
profileObject.identifiers = [{ type: "email", value: userEmail }];

const eventPayload = { event: eventObject, profile: profileObject };
url = `${baseEndpoint}users/${zendeskUserID}/events`;
const eventEndpoint = `${baseEndpoint}users/${zendeskUserID}/events`;

const response = responseBuilder(message, headers, eventPayload, url);
const response = responseBuilder(
message,
headers,
eventPayload,
eventEndpoint
);
return response;
}

Expand All @@ -606,7 +627,8 @@ async function processGroup(message, destinationConfig, headers, baseEndpoint) {
message,
category,
headers,
destinationConfig
destinationConfig,
baseEndpoint
);
url = baseEndpoint + category.createEndpoint;
} else {
Expand Down
59 changes: 59 additions & 0 deletions test/__mocks__/data/zendesk/response.json
Original file line number Diff line number Diff line change
Expand Up @@ -286,5 +286,64 @@
"next_page": null,
"previous_page": null,
"count": 1
},
"https://rudderlabtest1.zendesk.com/api/v2/users/search.json?query=testemail1@email": {
"users": [],
"next_page": null,
"previous_page": null,
"count": 0
},
"https://rudderlabtest2.zendesk.com/api/v2/users/search.json?query=testemail2@email": {
"users": [],
"next_page": null,
"previous_page": null,
"count": 0
},
"https://rudderlabtest1.zendesk.com/api/v2/users/create_or_update.json": {
"user": {
"id": 900113780483,
"url": "https://rudderlabtest1.zendesk.com/api/v2/users/900113780483.json",
"name": "John Wick",
"email": "testemail1@email",
"created_at": "2020-03-17T10:21:15Z",
"updated_at": "2020-03-23T15:56:56Z",
"time_zone": "Eastern Time (US & Canada)",
"iana_time_zone": "America/New_York",
"phone": null,
"shared_phone_number": null,
"photo": null,
"locale_id": 1,
"locale": "en-US",
"organization_id": 900001329943,
"role": "end-user",
"verified": true,
"external_id": "exId-123",
"tags": [],
"alias": null,
"active": true,
"shared": false,
"shared_agent": false,
"last_login_at": null,
"two_factor_auth_enabled": false,
"signature": null,
"details": null,
"notes": null,
"role_type": null,
"custom_role_id": null,
"moderator": false,
"ticket_restriction": "requested",
"only_private_comments": false,
"restricted_agent": true,
"suspended": false,
"chat_only": false,
"default_group_id": null,
"report_csv": false,
"user_fields": {
"birthday": null
}
}
},
"https://rudderlabtest2.zendesk.com/api/v2/users/create_or_update.json": {
"user": {}
}
}
78 changes: 78 additions & 0 deletions test/__tests__/data/zendesk_input.json
Original file line number Diff line number Diff line change
Expand Up @@ -1426,5 +1426,83 @@
"name": "name_abcd144"
}
}
},
{
"message": {
"anonymousId": "223b5f40-9543-4456-a7aa-945c43048185",
"channel": "web",
"context": {
"traits": {
"country": "UK",
"name": "John Wick",
"userId": "exId-123",
"email": "testemail1@email"
},
"userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
},
"event": "Order completed",
"messageId": "017f5227-ead3-4b7d-9794-1465022327be",
"originalTimestamp": "2021-03-25T14:36:47.695Z",
"properties": {
"category": "category",
"label": "label",
"userId": "exId-123",
"value": "value"
},
"rudderId": "d1b1b23f-c855-4b86-bad7-091f7bbe99fe",
"type": "track",
"userId": "0000000000"
},
"destination": {
"ID": "1qEz66UWpXTKwgCc8BPvyWPorpz",
"Name": "Zendesk",
"Config": {
"apiToken": "yPJwcLTFSsvIkFhY23SzittHoYADJQ7eKDoxNu4x",
"createUsersAsVerified": true,
"domain": "rudderlabtest1",
"email": "[email protected]",
"removeUsersFromOrganization": false,
"sendGroupCallsWithoutUserId": false
}
}
},
{
"message": {
"anonymousId": "223b5f40-9543-4456-a7aa-945c43048185",
"channel": "web",
"context": {
"traits": {
"country": "UK",
"name": "John Wick",
"userId": "exId-123",
"email": "testemail2@email"
},
"userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
},
"event": "Order completed",
"messageId": "017f5227-ead3-4b7d-9794-1465022327be",
"originalTimestamp": "2021-03-25T14:36:47.695Z",
"properties": {
"category": "category",
"label": "label",
"userId": "exId-123",
"value": "value"
},
"rudderId": "d1b1b23f-c855-4b86-bad7-091f7bbe99fe",
"type": "track",
"userId": "0000000000"
},
"destination": {
"ID": "1qEz66UWpXTKwgCc8BPvyWPorpz",
"Name": "Zendesk",
"Config": {
"apiToken": "yPJwcLTFSsvIkFhY23SzittHoYADJQ7eKDoxNu4x",
"createUsersAsVerified": true,
"domain": "rudderlabtest2",
"email": "[email protected]",
"removeUsersFromOrganization": false,
"sendGroupCallsWithoutUserId": false
}
}
}
]
50 changes: 49 additions & 1 deletion test/__tests__/data/zendesk_output.json
Original file line number Diff line number Diff line change
Expand Up @@ -548,5 +548,53 @@
},
"files": {}
}
]
],
{
"body": {
"FORM": {},
"JSON": {
"event": {
"description": "Order completed",
"properties": {
"category": "category",
"label": "label",
"userId": "exId-123",
"value": "value"
},
"source": "Rudder",
"type": "Order completed"
},
"profile": {
"identifiers": [
{
"type": "email",
"value": "testemail1@email"
}
],
"source": "Rudder",
"type": "Order completed"
}
},
"JSON_ARRAY": {},
"XML": {}
},
"endpoint": "https://rudderlabtest1.zendesk.com/api/v2/users/900113780483/events",
"files": {},
"headers": {
"Authorization": "Basic cnVkZGVybGFidGVzdDFAZW1haWwuY29tL3Rva2VuOnlQSndjTFRGU3N2SWtGaFkyM1N6aXR0SG9ZQURKUTdlS0RveE51NHg=",
"Content-Type": "application/json",
"X-Zendesk-Marketplace-App-Id": "263241",
"X-Zendesk-Marketplace-Name": "RudderStack",
"X-Zendesk-Marketplace-Organization-Id": "3339"
},
"method": "POST",
"params": {},
"type": "REST",
"userId": "223b5f40-9543-4456-a7aa-945c43048185",
"version": "1"
},
{
"statusCode": 400,
"error": "Failed to fetch user with email: testemail2@email due to Couldn't find user: John Wick"
}
]
Loading