Skip to content

Commit

Permalink
Disable logging API support (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
arjunu authored Jul 19, 2019
1 parent 661e9fc commit bdea409
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 27 deletions.
36 changes: 26 additions & 10 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
- `configuration` **[object][1]**
- `configuration.apiKey` **[string][2]**
- `configuration.hookURL` **[string][2]**
- `onMessage` **[function][3]** callback for incoming messages
- `configuration.conversationLogging` **[boolean][3]**
- `onMessage` **[function][4]** callback for incoming messages

Returns **[Promise][4]<[object][1]>** where object = {botName: string, history: Array[{content: string, made_by: string}]}
Returns **[Promise][5]<[object][1]>** where object = {botName: string, history: Array[{content: string, made_by: string}]}

## send

Expand All @@ -35,7 +36,7 @@ Sets callback for connection change

### Parameters

- `callback` **[function][3]** (isConnected: bool)
- `callback` **[function][4]** (isConnected: bool)

## attachToPayload

Expand Down Expand Up @@ -65,22 +66,36 @@ Removes a property from the payload object

- `key` **[string][2]**

## setConversationLogging

Turn conversation logging on or off

### Parameters

- `value` **[boolean][3]** true|false

## isConversationLogging

Check if conversation logging is on or off

Returns **[boolean][3]**

## getUserId

Returns a promise that resolves if and when user_id_cookie is available

Returns **[Promise][4]<[string][2]>**
Returns **[Promise][5]<[string][2]>**

## getBotName

Returns a Promise that resolves with bot name

### Parameters

- `hookURL` **[string][2]** (optional, default `store.hookURL`)
- `apiKey` **[string][2]** (optional, default `store.apiKey`)
- `hookURL` **[string][2]** (optional, default `store.configuration.hookURL`)
- `apiKey` **[string][2]** (optional, default `store.configuration.apiKey`)

Returns **[Promise][4]<([Response][5] | never)>**
Returns **[Promise][5]<([Response][6] | never)>**

## endSession

Expand All @@ -94,6 +109,7 @@ Returns **[Promise][4]<([Response][5] | never)>**

[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
[5]: https://developer.mozilla.org/docs/Web/Guide/HTML/HTML5
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
[6]: https://developer.mozilla.org/docs/Web/Guide/HTML/HTML5
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"name": "@twyla-ai/widget-core",
"version": "0.10.0",
"version": "0.11.0",
"description": "Twyla Widget Core",
"main": "dist/index.js",
"scripts": {
"build": "npm run clean && npx webpack --mode production",
"clean": "npx rimraf dist",
"documentation": "node document.js",
"pre-publish": "npm run build",
"publish": "npm publish --access public",
"test": "npx jest --no-cache ./src"
},
"author": "Twyla GmbH",
Expand Down
50 changes: 40 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ const getDefaultPayload = () => ({
});

const store = {
apiKey: undefined,
hookURL: undefined,
configuration: {
apiKey: undefined,
hookURL: undefined,
},
notificationsChannelURL: undefined,
userId: Cookies.get(COOKIE_NAME) || null,
payload: getDefaultPayload(),
Expand Down Expand Up @@ -165,7 +167,7 @@ const setUpSocket = () => {
store.socket.send(
JSON.stringify({
user_id_cookie: store.userId,
api_key: store.apiKey,
api_key: store.configuration.apiKey,
})
);
});
Expand All @@ -191,6 +193,7 @@ const setUpSocket = () => {
* @param {object} configuration
* @param {string} configuration.apiKey
* @param {string} configuration.hookURL
* @param {boolean} configuration.conversationLogging
* @param {function} onMessage callback for incoming messages
* @returns {Promise<object>}
* where object = {botName: string, history: Array[{content: string, made_by: string}]}
Expand All @@ -203,8 +206,14 @@ API.init = (configuration, onMessage) => {
// store promise to resolve on establish session success
store.promises.init = { resolve, reject };

store.apiKey = configuration.apiKey;
store.hookURL = configuration.hookURL;
store.configuration = {
apiKey: configuration.apiKey,
hookURL: configuration.hookURL,
};

if (configuration.conversationLogging === false) {
store.payload._logging_disabled = true;
}

try {
const { notificationsChannelURL, botName } = notificationsChannelURLFromHookURL(
Expand All @@ -229,8 +238,8 @@ API.init = (configuration, onMessage) => {
API.send = message => {
if (store.connected) {
postMessage({
url: store.hookURL,
apiKey: store.apiKey,
url: store.configuration.hookURL,
apiKey: store.configuration.apiKey,
input: message,
userId: store.userId,
payload: store.payload,
Expand Down Expand Up @@ -314,6 +323,26 @@ API.detachFromPayload = key => {
delete store.payload[key];
};

/**
* Turn conversation logging on or off
* @param {boolean} value true|false
*/
API.setConversationLogging = value => {
if (value === true) {
delete store.payload._logging_disabled;
} else if (value === false) {
store.payload._logging_disabled = true;
}
};

/**
* Check if conversation logging is on or off
* @returns {boolean}
*/
API.isConversationLogging = () => {
return !!!store.payload._logging_disabled;
};

/**
* Returns a promise that resolves if and when user_id_cookie is available
* @returns {Promise<string>}
Expand All @@ -334,7 +363,7 @@ API.getUserId = () => {
* @param {string} apiKey
* @returns {Promise<Response | never>}
*/
API.getBotName = (hookURL = store.hookURL, apiKey = store.apiKey) => {
API.getBotName = (hookURL = store.configuration.hookURL, apiKey = store.configuration.apiKey) => {
return fetch(`${hookURL}?key=${apiKey}`, {
method: 'GET',
}).then(response => {
Expand Down Expand Up @@ -368,8 +397,7 @@ API.endSession = () => {
API.clearSession = () => {
API.endSession();
store.userId = null;
store.apiKey = null;
store.hookURL = null;
store.configuration = {};
store.notificationsChannelURL = null;
store.payload = getDefaultPayload();
Cookies.remove(COOKIE_NAME);
Expand All @@ -385,6 +413,8 @@ export const {
attachToPayload,
detachFromPayload,
setMetadata,
isConversationLogging,
setConversationLogging,
getUserId,
getBotName,
clearSession,
Expand Down
81 changes: 76 additions & 5 deletions src/tests/api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
onConnectionChange,
send,
endSession,
isConversationLogging,
setConversationLogging,
} from '../index';
import { WebSocket, Server } from 'mock-socket';
import { CONVERSATION_STARTER } from '../constants';
Expand Down Expand Up @@ -70,9 +72,7 @@ describe('API test', () => {

const mockFetch = url => {
let json = f => f;
const fakeUrl = `https://api.demo.twyla.io/widget-hook/massive-dynamics/templates?key=${
configuration.apiKey
}`;
const fakeUrl = `https://api.demo.twyla.io/widget-hook/massive-dynamics/templates?key=${configuration.apiKey}`;

if (url === fakeUrl) {
json = () => ({ name: 'Templates' });
Expand Down Expand Up @@ -229,14 +229,85 @@ describe('API test', () => {

expect(global.fetch.mock.calls.length).toEqual(2);
expect(global.fetch.mock.calls[1][0]).toEqual(configuration.hookURL);
expect(global.fetch.mock.calls[1][1]).toEqual(postMsg('blue', { fruit: 'apple' }));

let requestPayload = global.fetch.mock.calls[1][1];
expect(requestPayload.method).toEqual('POST');
expect(JSON.parse(requestPayload.body)).toEqual({
api_key: 'fakeApiKey',
data: {
_meta: {
origin: 'https://jest-test.com',
pathname: '/widget.html',
},
fruit: 'apple',
},
input: 'blue',
user_id_cookie: 'fakeUserIdCookie',
});

detachFromPayload('fruit');
send('green');

expect(global.fetch.mock.calls.length).toEqual(3);
expect(global.fetch.mock.calls[2][0]).toEqual(configuration.hookURL);
expect(global.fetch.mock.calls[2][1]).toEqual(postMsg('green'));

requestPayload = global.fetch.mock.calls[2][1];
expect(requestPayload.method).toEqual('POST');
expect(JSON.parse(requestPayload.body)).toEqual({
api_key: 'fakeApiKey',
data: {
_meta: {
origin: 'https://jest-test.com',
pathname: '/widget.html',
},
},
input: 'green',
user_id_cookie: 'fakeUserIdCookie',
});

done();
});
});

test('toggle logging', done => {
init({ ...configuration, conversationLogging: false }, onMessage).then(() => {
expect(isConversationLogging()).toEqual(false);

send('blue');

let requestPayload = global.fetch.mock.calls[1][1];
expect(requestPayload.method).toEqual('POST');
expect(JSON.parse(requestPayload.body)).toEqual({
api_key: 'fakeApiKey',
data: {
_meta: {
origin: 'https://jest-test.com',
pathname: '/widget.html',
},
_logging_disabled: true,
},
input: 'blue',
user_id_cookie: 'fakeUserIdCookie',
});

setConversationLogging(true);

expect(isConversationLogging()).toEqual(true);

send('green');

requestPayload = global.fetch.mock.calls[2][1];
expect(JSON.parse(requestPayload.body)).toEqual({
api_key: 'fakeApiKey',
data: {
_meta: {
origin: 'https://jest-test.com',
pathname: '/widget.html',
},
},
input: 'green',
user_id_cookie: 'fakeUserIdCookie',
});

done();
});
Expand Down

0 comments on commit bdea409

Please sign in to comment.