-
Notifications
You must be signed in to change notification settings - Fork 2
zendesk support #52
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
Draft
kibin
wants to merge
3
commits into
master
Choose a base branch
from
feature/zd_support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
zendesk support #52
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,7 @@ | ||
/* global window */ | ||
'use strict' | ||
|
||
const VERSION = '1.0.3' | ||
const VERSION = '1.0.3-f' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: fix when master branch is published |
||
const SDK_NAME = 'Intento.NodeJS' | ||
|
||
const DEFAULT_AWAIT_DELAY = 1000 | ||
|
@@ -16,6 +16,37 @@ const { | |
} = require('./utils') | ||
const HOST = process.env.INTENTO_API_HOST || 'api.inten.to' | ||
|
||
/** | ||
* Default fetcher based on https.request | ||
* | ||
* @returns {undefined} | ||
*/ | ||
function defaultFetcher({ requestOptions, debug, verbose, data, content }) { | ||
return new Promise((resolve, reject) => { | ||
|
||
try { | ||
const req = https.request(requestOptions, resp => | ||
responseHandler(resp, resolve, reject, debug, verbose) | ||
) | ||
|
||
req.on('error', function (err) { | ||
if (err.code === 'ENOTFOUND') { | ||
console.error('Host look up failed: \n', err) | ||
console.log('\nPlease, check internet connection\n') | ||
} else { | ||
customErrorLog(err, 'Fails getting a response from the API') | ||
} | ||
}) | ||
req.on('timeout', function (err) { | ||
customErrorLog(err, 'Are you offline?') | ||
}) | ||
req.write(data || JSON.stringify(content) || '') | ||
req.end() | ||
} catch (e) { | ||
customErrorLog(e, 'Fails to send a request to the API') | ||
} | ||
}) | ||
} | ||
/** | ||
* Main class for connectiong to Intento API | ||
* Typical usage: | ||
|
@@ -32,6 +63,7 @@ function IntentoConnector(credentials = {}, options = {}) { | |
curl = false, | ||
dryRun = false, | ||
userAgent, | ||
fetcher = defaultFetcher | ||
} = options | ||
if (typeof credentials === 'string') { | ||
this.credentials = { apikey: credentials } | ||
|
@@ -45,7 +77,7 @@ function IntentoConnector(credentials = {}, options = {}) { | |
this.verbose = verbose | ||
this.dryRun = dryRun | ||
this.userAgent = userAgent | ||
|
||
this.fetcher = fetcher | ||
const { apikey, host = HOST } = this.credentials | ||
|
||
if (!apikey) { | ||
|
@@ -250,33 +282,12 @@ IntentoConnector.prototype.makeRequest = function (options = {}) { | |
console.log(`\nTest request\n${requestString}`) | ||
} | ||
|
||
return new Promise((resolve, reject) => { | ||
if (this.dryRun) { | ||
resolve(data || content || requestOptions.path || '') | ||
} | ||
if (this.dryRun) { | ||
return Promise.resolve(data || content || requestOptions.path || '') | ||
} | ||
|
||
try { | ||
const req = https.request(requestOptions, resp => | ||
responseHandler(resp, resolve, reject, this.debug, this.verbose) | ||
) | ||
return this.fetcher({ requestOptions, debug: this.debug, verbose: this.verbose, data, content }) | ||
|
||
req.on('error', function (err) { | ||
if (err.code === 'ENOTFOUND') { | ||
console.error('Host look up failed: \n', err) | ||
console.log('\nPlease, check internet connection\n') | ||
} else { | ||
customErrorLog(err, 'Fails getting a response from the API') | ||
} | ||
}) | ||
req.on('timeout', function (err) { | ||
customErrorLog(err, 'Are you offline?') | ||
}) | ||
req.write(data || JSON.stringify(content) || '') | ||
req.end() | ||
} catch (e) { | ||
customErrorLog(e, 'Fails to send a request to the API') | ||
} | ||
}) | ||
} | ||
|
||
IntentoConnector.prototype.fulfill = function (slug, parameters = {}) { | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
'use strict' | ||
const fetch = require('node-fetch') | ||
const IntentoConnector = require('../src/index') | ||
|
||
// Quickly load .env files into the environment | ||
require('dotenv').load() | ||
const apikey = process.env.INTENTO_API_KEY | ||
const host = process.env.INTENTO_API_HOST | ||
|
||
const DEBUG = false | ||
|
||
/** | ||
* ZD Client mockup | ||
* | ||
* https://developer.zendesk.com/apps/docs/developer-guide/using_sdk#using-secure-settings | ||
* @param {*} params all the params | ||
* @returns {undefined} | ||
*/ | ||
class ZDClient { | ||
|
||
request(params) { | ||
|
||
const { | ||
url, | ||
headers, | ||
secure, | ||
type, | ||
contentType, | ||
data, | ||
} = params | ||
|
||
|
||
if (secure) { | ||
for (const key in headers) { | ||
headers[key] = headers[key].replace('{{setting.token}}', apikey) | ||
} | ||
} | ||
|
||
return fetch(url, { | ||
method: type, | ||
headers: { ...headers, 'content-type': contentType }, | ||
body: type !== 'GET' ? data : undefined | ||
}).then(response => { | ||
// here mimicing zd request API as we understand it | ||
// | ||
|
||
// zd request API: https://developer.zendesk.com/apps/docs/core-api/client_api#client.requestoptions | ||
// | ||
// console.log(response.responseJSON); // body of the HTTP response | ||
// console.log(response.responseText); // body of the HTTP response | ||
// console.log(response.status); // HTTP response status | ||
// console.log(response.statusText); // Is either 'success' or 'error' | ||
// console.log(response.headers); // HTTP response headers | ||
|
||
const { status, headers } = response | ||
|
||
return response.text().then(bodytext => { | ||
// it's not exactly clear whether JSON parsing error | ||
// forces zd request to return 'error', but let's consider this as true for now | ||
const zdResponse = { responseText: bodytext, status, statusText: 'error', headers } | ||
try { | ||
zdResponse.responseJSON = JSON.parse(bodytext) | ||
zdResponse.statusText = 'success' | ||
} catch (exception) { | ||
zdResponse.error = exception | ||
} | ||
|
||
return zdResponse | ||
}) | ||
}) | ||
} | ||
} | ||
|
||
const zdclient = new ZDClient() | ||
const HTTP_CODES = { | ||
404: 'Not Found' | ||
} | ||
/** | ||
* Fetcher function which can work with zendesk client | ||
* @param {*} param0 incoming parameters | ||
* @returns {undefined} | ||
*/ | ||
function zdfetcher({ requestOptions, /*debug, verbose,*/ data, content }) { | ||
// console.log('zd fetcher ', requestOptions, data, content) | ||
let { headers, host, path, method } = requestOptions | ||
|
||
delete headers["content-type"] | ||
headers.apikey = "{{setting.token}}" | ||
return zdclient.request({ | ||
url: `https://${host}${path}`, // for ex. api.inten.to/ai/text/translate | ||
headers, | ||
secure: true, | ||
type: method, // POST, GET, etc | ||
contentType: 'application/json', | ||
data: data || JSON.stringify(content) || '' | ||
}).then(zdresponse => { | ||
// console.log(' got zdresponse ', zdresponse) | ||
const { status, statusText } = zdresponse | ||
|
||
// default fetcher treats 404 as errors and throws, so should we | ||
|
||
// here other non 200 statues should be checked | ||
if (statusText === 'success' && status !== 404) { | ||
return zdresponse.responseJSON | ||
} | ||
|
||
// might be that zd request returns actual statusMessage in some undocumented field | ||
let error = { statusCode: status, statusMessage: HTTP_CODES[status] } | ||
try { | ||
error.error = zdresponse.responseJSON.error | ||
} | ||
catch (exception) { | ||
error.error = exception | ||
} | ||
throw error | ||
}) | ||
|
||
} | ||
|
||
|
||
|
||
const client_for_zd = new IntentoConnector({ apikey, host }, { debug: DEBUG, fetcher: zdfetcher }) | ||
|
||
describe('zd fetcher test', () => { | ||
it('get translation', async () => { | ||
expect.assertions(10) | ||
const translate = await client_for_zd.ai.text.translate.fulfill({ | ||
text: 'A sample text', | ||
to: 'es', | ||
}) | ||
if (DEBUG) { | ||
console.info('Current apikey settings: ', translate) | ||
} | ||
|
||
expect(translate).toBeInstanceOf(Object) | ||
expect(translate.hasOwnProperty('id')).toBeTruthy() | ||
expect(translate.hasOwnProperty('done')).toBeTruthy() | ||
expect(translate.hasOwnProperty('response')).toBeTruthy() | ||
expect(translate.hasOwnProperty('meta')).toBeTruthy() | ||
expect(translate.hasOwnProperty('error')).toBeTruthy() | ||
|
||
const res = translate.response[0] | ||
expect(res).toBeDefined() | ||
expect(res.hasOwnProperty('results')).toBeTruthy() | ||
expect(res.hasOwnProperty('meta')).toBeTruthy() | ||
expect(res.hasOwnProperty('service')).toBeTruthy() | ||
}) | ||
|
||
|
||
it('fails without options specified', async () => { | ||
expect.assertions(2) | ||
await client_for_zd.makeRequest().catch(e => { | ||
expect(e.statusCode).toEqual(404) | ||
expect(e.statusMessage).toEqual('Not Found') | ||
}) | ||
}) | ||
|
||
it('fails with an incorrect path specified: /', async () => { | ||
expect.assertions(2) | ||
await client_for_zd.makeRequest({ path: '/' }).catch(e => { | ||
expect(e.statusCode).toEqual(404) | ||
expect(e.statusMessage).toEqual('Not Found') | ||
}) | ||
}) | ||
|
||
it('fails with an incorrect path specified: /settings', async () => { | ||
expect.assertions(3) | ||
await client_for_zd.makeRequest({ path: '/settings' }).catch(e => { | ||
expect(e.error).toBeDefined() | ||
expect(e.error.code).toEqual(404) | ||
expect(e.error.message).toEqual('no such intent settings/') | ||
}) | ||
}) | ||
|
||
it('fails with an incorrect path specified: /ai', async () => { | ||
expect.assertions(3) | ||
await client_for_zd.makeRequest({ path: '/ai' }).catch(e => { | ||
expect(e.error).toBeDefined() | ||
expect(e.error.code).toEqual(404) | ||
expect(e.error.message).toEqual('no such intent ai/') | ||
}) | ||
}) | ||
|
||
it('fails with an incorrect path specified: /usage', async () => { | ||
expect.assertions(2) | ||
await client_for_zd | ||
.makeRequest({ path: '/usage' }) | ||
.catch(e => { | ||
expect(e.error).toBeDefined() | ||
expect(e.error).toEqual('No such endpoint.') | ||
// expect(e.error.code).toEqual(404) | ||
// expect(e.error.message).toEqual('No such endpoint.') | ||
}) | ||
}) | ||
|
||
it('shows settings/languages', async () => { | ||
expect.assertions(1) | ||
const langSettings = await client_for_zd.makeRequest({ | ||
path: '/settings/languages', | ||
}) | ||
if (DEBUG) { | ||
console.info('Current apikey settings: ', langSettings) | ||
} | ||
|
||
expect(langSettings).toBeInstanceOf(Object) | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
removed tests, because without api key they don't work, and so yarn@3 can't pack it directly from github