1
0
mirror of synced 2024-11-28 07:06:02 +03:00

Merge pull request #5 from iyzoer/master

es6 syntax
This commit is contained in:
Alex Lushpai 2019-03-07 11:07:28 +03:00 committed by GitHub
commit 8598c68426
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 818 additions and 451 deletions

3
.babelrc Normal file
View File

@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env"]
}

3
.gitignore vendored
View File

@ -60,4 +60,7 @@ typings/
# next.js build output # next.js build output
.next .next
.idea .idea
package-lock.json package-lock.json
out/
dist/

View File

@ -1,6 +1,19 @@
language: node_js language: node_js
node_js: node_js:
- "11" - "11"
- "10" - "10"
- "8" - "8"
script: npm run test script: npm run test
after_success: npm run doc
deploy:
provider: pages
skip-cleanup: true
github-token: $GITHUB_TOKEN
keep-history: true
local-dir: out
on:
branch: master

View File

@ -12,17 +12,24 @@ This is js retailCRM bot API client.
npm install --save mg-api-client npm install --save mg-api-client
``` ```
In your file In your file
###### CommonJS
``` ```
var RetailcrmBotApiClient = require('mg-api-client'); var MgBotApiClient = require('mg-api-client');
``` ```
###### es6
```
import MgBotApiClient from 'mg-api-client';
```
# Usage # Usage
#### Get users #### Get users
```javascript ```javascript
var api = new RetailcrmBotApiClient({ const api = new MgBotApiClient({
host: 'https://api.example.com', host: 'https://api.example.com',
token: 'your bot token', token: 'your bot token',
apiVersion: 'v1' // optional apiVersion: 'v1' // optional
}).getClient(); }).client;
api.getUsers() api.getUsers()
.then(function (users) { .then(function (users) {
@ -35,13 +42,13 @@ api.getUsers()
#### Send message #### Send message
```javascript ```javascript
var api = new RetailcrmBotApiClient({ const api = new MgBotApiClient({
host: 'https://api.example.com', host: 'https://api.example.com',
token: 'your bot token', token: 'your bot token',
apiVersion: 'v1' // optional apiVersion: 'v1' // optional
}).getClient(); }).client;
var message = { let message = {
chat_id: 1, chat_id: 1,
content: 'Text message', content: 'Text message',
scope: 'public', scope: 'public',
@ -56,3 +63,38 @@ api.sendMessage(message)
console.log(e); console.log(e);
}); });
``` ```
#### Websocket Example
```javascript
const WebSocket = require('ws');
const api = new MgBotApiClient({
host: 'https://api.example.com',
token: 'your bot token',
apiVersion: 'v1' // optional
}).client;
const wsData = api.getWebsocketData([MgBotApiClient.types().wsMessageNew]);
const ws = new WebSocket(wsData.get('url'), {
headers: wsData.get('headers')
});
ws.on('message', function (content) {
let event = JSON.parse(content);
let data = event.data;
if (event.type === 'message_new' && data.message.from.type !== 'bot') {
let message = {
chat_id: data.message.chat_id,
content: 'Bonjour!',
scope: 'public',
type: 'text'
};
api.sendMessage(message).then(function (res) {
console.log(res);
}).catch(function (e) {
console.log(e);
})
}
});
```

View File

@ -1,16 +1,17 @@
'use strict'; 'use strict';
var v1 = require('./lib/v1/client'); import v1 from './lib/v1/client'
var request = require('./lib/request'); import Request from './lib/request'
import * as consts from './lib/consts'
module.exports = RetailcrmBotApiClient; const lastApiVersion = 'v1';
/** export default class MgBotApiClient {
/**
* @param {Object} options * @param {Object} options
* @throws {Error} * @throws {Error}
* @constructor
*/ */
function RetailcrmBotApiClient(options) { constructor(options) {
if (!options.host) { if (!options.host) {
throw new Error('Url is required'); throw new Error('Url is required');
} }
@ -23,11 +24,10 @@ function RetailcrmBotApiClient(options) {
throw new Error('Token is required'); throw new Error('Token is required');
} }
var currentVersion; let currentVersion;
var lastApiVersion = 'v1';
var clients = { const clients = {
'v1': v1.Client 'v1': v1
}; };
if (options.apiVersion) { if (options.apiVersion) {
@ -36,13 +36,22 @@ function RetailcrmBotApiClient(options) {
currentVersion = lastApiVersion; currentVersion = lastApiVersion;
} }
this._client = new clients[currentVersion](new request.Request(options)); this._client = new clients[currentVersion](new Request(options));
} }
/** /**
* Get API client * Get API client
* @returns {Client} * @returns {Client}
*/ */
RetailcrmBotApiClient.prototype.getClient = function () { get client() {
return this._client; return this._client;
}; };
/**
* Get types
* @returns {{msgTypeOrder?: string, wsUserJoinedChat?: string, msgTypeImage?: string, wsDialogAssign?: string, msgTypeText?: string, messageScopePublic?: string, wsMessageDeleted?: string, msgTypeCommand?: string, msgTypeFile?: string, msgTypeSystem?: string, wsBotUpdated?: string, msgTypeProduct?: string, wsDialogClosed?: string, wsMessageNew?: string, wsMessageUpdated?: string, wsSettingsUpdated?: string, wsUserUpdated?: string, wsCustomerUpdated?: string, wsChatCreated?: string, wsUserLeftChat?: string, wsChannelUpdated?: string, wsDialogOpened?: string, messageScopePrivate?: string, wsUserOnlineUpdated?: string, wsChatUnreadUpdated?: string, wsChatUpdated?: string}}
*/
static types() {
return consts;
}
}

212
lib/consts.js Normal file
View File

@ -0,0 +1,212 @@
/**
* New message websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsMessageNew
*/
export const wsMessageNew = 'message_new';
/**
* Updating message websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsMessageUpdated
*/
export const wsMessageUpdated = 'message_updated';
/**
* Websocket event delete message
* @constant
* @type {string}
* @example MgBotApiClient.types().wsMessageDeleted
*/
export const wsMessageDeleted = 'message_deleted';
/**
* Dialogue opening websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsDialogOpened
*
*/
export const wsDialogOpened = 'dialog_opened';
/**
* Dialogue closing websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsDialogClosed
*/
export const wsDialogClosed = 'dialog_closed';
/**
* Dialogue appointment websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsDialogAssign
*/
export const wsDialogAssign = 'dialog_assign';
/**
* Chat creating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsChatCreated
*/
export const wsChatCreated = 'chat_created';
/**
* Chat updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsChatUpdated
*/
export const wsChatUpdated = 'chat_updated';
/**
* Unread chat updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsChatUnreadUpdated
*/
export const wsChatUnreadUpdated = 'chat_unread_updated';
/**
* User online status updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsUserOnlineUpdated
*/
export const wsUserOnlineUpdated = 'user_online_updated';
/**
* User joined chat websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsUserJoinedChat
*/
export const wsUserJoinedChat = 'user_joined_chat';
/**
* User left chat websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsUserLeftChat
*
*/
export const wsUserLeftChat = 'user_left_chat';
/**
* User updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsUserUpdated
*/
export const wsUserUpdated = 'user_updated';
/**
* Customer updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsCustomerUpdated
*/
export const wsCustomerUpdated = 'customer_updated';
/**
* Bot updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsBotUpdated
*
*/
export const wsBotUpdated = 'bot_updated';
/**
* Channel updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsChannelUpdated
*/
export const wsChannelUpdated = 'channel_updated';
/**
* Settings updating websocket event
* @constant
* @type {string}
* @example MgBotApiClient.types().wsSettingsUpdated
*/
export const wsSettingsUpdated = 'settings_updated';
/**
* Public message scope
* @constant
* @type {string}
* @example MgBotApiClient.types().messageScopePublic
*/
export const messageScopePublic = 'public';
/**
* Public message scope
* @constant
* @type {string}
* @example MgBotApiClient.types().messageScopePrivate
*/
export const messageScopePrivate = 'private';
/**
* Text message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeText
*/
export const msgTypeText = 'text';
/**
* System message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeSystem
*/
export const msgTypeSystem = 'system';
/**
* Command message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeCommand
*/
export const msgTypeCommand = 'command';
/**
* Order message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeOrder
*/
export const msgTypeOrder = 'order';
/**
* Product message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeProduct
*/
export const msgTypeProduct = 'product';
/**
* File message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeFile
*/
export const msgTypeFile = 'file';
/**
* Image message type
* @constant
* @type {string}
* @example MgBotApiClient.types().msgTypeImage
*/
export const msgTypeImage = 'image';

View File

@ -1,31 +1,41 @@
'use strict'; 'use strict';
var url = require('url'); import url from 'url'
var https = require('https'); import https from 'https'
var querystring = require('querystring'); import querystring from 'querystring'
exports.Request = Request; export default class Request {
/**
/**
* @param {Object} options * @param {Object} options
* @constructor * @constructor
*/ */
function Request(options) { constructor(options) {
/**
* @prop System host
* @type {string}
* @private
*/
this._host = url.parse(options.host).host; this._host = url.parse(options.host).host;
this._token = options.token;
}
/** /**
* @prop Bot token
* @type {*|string|string}
* @private
*/
this._token = options.token;
}
/**
* Get request path * Get request path
* @param {string} endpoint * @param {string} endpoint
* @returns {string} * @returns {string}
* @private * @private
*/ */
Request.prototype._getPath = function (endpoint) { _getPath(endpoint) {
return '/api/bot/' + endpoint; return '/api/bot/' + endpoint;
}; }
/** /**
* Make request * Make request
* @param {string} endpoint * @param {string} endpoint
* @param {string} method * @param {string} method
@ -34,32 +44,32 @@ Request.prototype._getPath = function (endpoint) {
* @throws {Error} * @throws {Error}
* @private * @private
*/ */
Request.prototype._request = function (endpoint, method, data) { _request(endpoint, method, data = {}) {
var path = this._getPath(endpoint); let path = this._getPath(endpoint);
var response = ''; let response = '';
if (method === 'GET' && data.length > 0) { if (method === 'GET' && data.length > 0) {
path += '?' + querystring.stringify(data); path += '?' + querystring.stringify(data);
} }
var options = { const options = {
host: this._host, host: this._host,
method: method, method: method,
path: path, path: path,
headers: { headers: {
'x-bot-token': this._token 'X-Bot-Token': this._token
} }
}; };
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
var request = https.request(options, function (res) { const request = https.request(options, function (res) {
res.on('data', function (chunk) { res.on('data', function (chunk) {
response += chunk; response += chunk;
}); });
res.on('end', function () { res.on('end', function () {
try { try {
var result = JSON.parse(response); const result = JSON.parse(response);
if (res.statusCode < 400) { if (res.statusCode < 400) {
resolve(result); resolve(result);
@ -86,76 +96,85 @@ Request.prototype._request = function (endpoint, method, data) {
reject(e); reject(e);
}); });
}); });
}; }
/** /**
* Method GET * Method GET
* @param {string} endpoint * @param {string} endpoint
* @param {Object} params * @param {Object} params
* @returns {Promise} * @returns {Promise}
*/ */
Request.prototype.get = function (endpoint, params) { get(endpoint, params = {}) {
if (params === undefined) { return this._request(endpoint, 'GET', params);
params = {};
} }
return this._request(endpoint, 'GET', params); /**
};
/**
* Method POST * Method POST
* @param {string} endpoint * @param {string} endpoint
* @param {Object} data * @param {Object} data
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
*/ */
Request.prototype.post = function (endpoint, data) { post(endpoint, data) {
if (!data) { if (!data) {
throw new Error('Body is not be empty'); throw new Error('Body is not be empty');
} }
return this._request(endpoint, 'POST', data); return this._request(endpoint, 'POST', data);
}; };
/** /**
* Method PATCH * Method PATCH
* @param {string} endpoint * @param {string} endpoint
* @param {Object} data * @param {Object} data
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
*/ */
Request.prototype.patch = function (endpoint, data) { patch(endpoint, data) {
if (!data) { if (!data) {
throw new Error('Body is not be empty'); throw new Error('Body is not be empty');
} }
return this._request(endpoint, 'PATCH', data); return this._request(endpoint, 'PATCH', data);
}; }
/** /**
* Method PUT * Method PUT
* @param {string} endpoint * @param {string} endpoint
* @param {Object} data * @param {Object} data
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
*/ */
Request.prototype.put = function (endpoint, data) { put(endpoint, data) {
if (!data) { if (!data) {
throw new Error('Body is not be empty'); throw new Error('Body is not be empty');
} }
return this._request(endpoint, 'PUT', data); return this._request(endpoint, 'PUT', data);
}; }
/** /**
* Method DELETE * Method DELETE
* @param {string} endpoint * @param {string} endpoint
* @returns {Promise} * @returns {Promise}
*/ */
Request.prototype.delete = function (endpoint) { delete(endpoint) {
return this._request(endpoint, 'DELETE', {}); return this._request(endpoint, 'DELETE');
}; }
Request.prototype.getHost = function () { /**
* Get api host
* @returns {string | *}
*/
get host() {
return this._host; return this._host;
}; }
/**
* Get bot token
* @returns {*|string}
*/
get token() {
return this._token;
}
}

View File

@ -1,204 +1,229 @@
'use strict'; 'use strict';
exports.Client = Client; /** @class Client */
export default class Client {
/** constructor(request) {
* @param {Request} request
* @constructor
*/
function Client(request) {
this._version = 'v1'; this._version = 'v1';
this._request = request; this._request = request;
} }
/** /**
* Get bots * Get bots
* @param {string} params * @param {Object} params - Filter's object for bots
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getBots = function (params) { getBots(params = {}) {
return this._request.get(this._version + '/bots', params); return this._request.get(this._version + '/bots', params);
}; };
/** /**
* Get channels * Get channels
* @param {string} params * @param {Object} params - Filter's object for channels
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getChannels = function (params) { getChannels(params = {}) {
return this._request.get(this._version + '/channels', params); return this._request.get(this._version + '/channels', params);
}; };
/** /**
* Get chats * Get chats
* @param {string} params * @param {Object} params - Filter's object for chats
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getChats = function (params) { getChats(params = {}) {
return this._request.get(this._version + '/chats', params); return this._request.get(this._version + '/chats', params);
}; };
/** /**
* Get customers * Get customers
* @param {string} params * @param {Object} params - Filter's object for customers
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getCustomers = function (params) { getCustomers(params = {}) {
return this._request.get(this._version + '/customers', params); return this._request.get(this._version + '/customers', params);
}; };
/** /**
* Get dialogs * Get dialogs
* @param {string} params * @param {Object} params - Filter's object for dialogs
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getDialogs = function (params) { getDialogs(params = {}) {
return this._request.get(this._version + '/dialogs', params); return this._request.get(this._version + '/dialogs', params);
}; };
/** /**
* Get members * Get members
* @param {string} params * @param {Object} params - Filter's object for members
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getMembers = function (params) { getMembers(params = {}) {
return this._request.get(this._version + '/members', params); return this._request.get(this._version + '/members', params);
}; };
/** /**
* Assign dialog * Assign dialog
* @param {Number} dialog_id * @param {Number} dialog_id - Dialog id
* @param {Object} dialog * @param {Object} dialog - Dialog object
* @returns {Promise}
*/
Client.prototype.assignDialog = function (dialog_id, dialog) {
return this._request.patch(this._version + '/dialogs/'+ dialog_id + '/assign', dialog);
};
/**
* Close dialog
* @param {Number} dialog_id
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
* @memberOf Client
*/ */
Client.prototype.closeDialog = function (dialog_id) { assignDialog(dialog_id, dialog) {
if (!dialog_id) { if (!dialog_id) {
throw new Error('dialog_id is required'); throw new Error('Parameter `dialog_id` is required');
}
return this._request.patch(this._version + '/dialogs/'+ dialog_id + '/assign', dialog);
};
/**
* Close dialog
* @param {Number} dialog_id - Dialog id
* @returns {Promise}
* @throws {Error}
* @memberOf Client
*/
closeDialog(dialog_id) {
if (!dialog_id) {
throw new Error('Parameter `dialog_id` is required');
} }
return this._request.delete(this._version + '/dialogs/'+ dialog_id + '/close'); return this._request.delete(this._version + '/dialogs/'+ dialog_id + '/close');
}; };
/** /**
* Send message * Send message
* @param {Object} data * @param {Object} message - Message object
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.sendMessage = function (data) { sendMessage(message) {
return this._request.post(this._version + '/messages', data); return this._request.post(this._version + '/messages', message);
}; };
/** /**
* Get messages * Get messages
* @param {Object} params * @param {Object} params - Filter's object for messages
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getMessages = function (params) { getMessages(params = {}) {
return this._request.get(this._version + '/messages', params); return this._request.get(this._version + '/messages', params);
}; };
/** /**
* Delete message * Delete message
* @param {Number} message_id * @param {Number} message_id - Message id
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
* @memberOf Client
*/ */
Client.prototype.deleteMessage = function (message_id) { deleteMessage(message_id) {
if (!message_id) { if (!message_id) {
throw new Error('message_id is required'); throw new Error('Parameter `message_id` is required');
} }
return this._request.delete(this._version + '/messages/' + message_id); return this._request.delete(this._version + '/messages/' + message_id);
}; };
/** /**
* Edit message * Edit message
* @param {Number} message_id * @param {Number} message_id - Message id
* @param {Object} message * @param {Object} message - Message object
* @returns {Promise}
*/
Client.prototype.editMessage = function (message_id, message) {
return this._request.patch(this._version + '/messages/' + message_id, message);
};
/**
* Get bot commands
* @param {Object} params
* @returns {Promise}
*/
Client.prototype.getCommands = function (params) {
return this._request.get(this._version + '/my/commands', params);
};
/**
* Edit bot command
* @param {string} command_name
* @param {Object} data
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
* @memberOf Client
*/ */
Client.prototype.editCommand = function (command_name, data) { editMessage(message_id, message) {
if (!command_name) { if (!message_id) {
throw new Error('Parameter command name is required'); throw new Error('Parameter `message_id` is required');
} }
return this._request.put(this._version + '/my/commands/' + command_name, data); return this._request.patch(this._version + '/messages/' + message_id, message);
}; };
/** /**
* Delete bot command * Get bot commands
* @param {string} command_name * @param {Object} params - Filter's object for commands
* @returns {Promise}
* @memberOf Client
*/
getCommands(params = {}) {
return this._request.get(this._version + '/my/commands', params);
};
/**
* Edit bot command
* @param {string} command_name - Command name
* @param {Object} command - Command object
* @returns {Promise} * @returns {Promise}
* @throws {Error} * @throws {Error}
* @memberOf Client
*/ */
Client.prototype.deleteCommand = function (command_name) { editCommand(command_name, command) {
if (!command_name) { if (!command_name) {
throw new Error('command_name is required'); throw new Error('Parameter `command_name` is required');
}
return this._request.put(this._version + '/my/commands/' + command_name, command);
};
/**
* Delete bot command
* @param {string} command_name - Command name
* @returns {Promise}
* @throws {Error}
* @memberOf Client
*/
deleteCommand(command_name) {
if (!command_name) {
throw new Error('Parameter `command_name` is required');
} }
return this._request.delete(this._version + '/my/commands/' + command_name); return this._request.delete(this._version + '/my/commands/' + command_name);
}; };
/** /**
* Bot information update * Bot information update
* @param {Object} data * @param {Object} data - Bot data
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.info = function (data) { info(data) {
return this._request.patch(this._version + '/my/info', data); return this._request.patch(this._version + '/my/info', data);
}; };
/** /**
* Get users * Get users
* @param {Object} params * @param {Object} params - Filter's object for users
* @returns {Promise} * @returns {Promise}
* @memberOf Client
*/ */
Client.prototype.getUsers = function (params) { getUsers(params = {}) {
return this._request.get(this._version + '/users', params); return this._request.get(this._version + '/users', params);
}; };
/** /**
* Get websocket url * Get websocket url
* @param {array<string>} events * @param {array<string>} events - Array of strings with websocket events
* @returns {string} * @returns {Map}
* @throws {Error} * @throws {Error}
* @memberOf Client
*/ */
Client.prototype.getWebsocketUrl = function (events) { getWebsocketData(events) {
if (!events) { if (!events) {
throw new Error('Events is required'); throw new Error('Events is required');
} }
var url = 'wss://' + this._request.getHost() + '/api/bot/' + this._version + '/ws?events='; let map = new Map();
let url = 'wss://' + this._request.host + '/api/bot/' + this._version + '/ws?events=';
events.forEach(function (event) { events.forEach(function (event) {
url += event + ','; url += event + ',';
@ -206,5 +231,11 @@ Client.prototype.getWebsocketUrl = function (events) {
url = url.slice(0, -1); url = url.slice(0, -1);
return url; map.set('url', url);
}; map.set('headers', {
'X-Bot-Token': this._request.token
});
return map;
};
}

View File

@ -1,22 +1,39 @@
{ {
"name": "mg-api-client", "name": "mg-api-client",
"description": "JS client for retailCRM Bot API", "description": "JS client for retailCRM Bot API",
"tags": ["API", "retailCRM", "Bot", "Chat"], "tags": [
"API",
"retailCRM",
"Bot",
"Chat"
],
"version": "1.0.1", "version": "1.0.1",
"scripts": { "scripts": {
"test": "./node_modules/.bin/_mocha ./tests/." "doc": "./node_modules/.bin/jsdoc lib/v1/client.js lib/consts.js -R README.md",
"build": "./node_modules/.bin/rollup -c",
"test": "./node_modules/.bin/_mocha --require @babel/register ./tests/."
}, },
"author": "retailCRM", "author": "retailCRM",
"license": "MIT", "license": "MIT",
"main": "index.js", "main": "./dist/index.js",
"bugs": { "bugs": {
"url": "https://github.com/retailcrm/mg-bot-api-client-js/issues" "url": "https://github.com/retailcrm/mg-bot-api-client-js/issues"
}, },
"dependencies": {}, "dependencies": {},
"devDependencies": { "devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.3",
"@babel/preset-env": "^7.3.1",
"@babel/register": "^7.0.0",
"babelrc-rollup": "^3.0.0",
"chai": "^4.2.0", "chai": "^4.2.0",
"jsdoc": "^3.5.5",
"mocha": "^5.2.0", "mocha": "^5.2.0",
"nock": "^10.0.6" "nock": "^10.0.6",
"rollup": "^1.2.2",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0"
}, },
"engines": { "engines": {
"node": ">= 4.0.0" "node": ">= 4.0.0"

17
rollup.config.js Normal file
View File

@ -0,0 +1,17 @@
import babel from 'rollup-plugin-babel';
let pluginOptions = [
babel({
exclude: 'node_modules/**',
}),
];
export default [{
input: 'index.js',
output: {
name: 'main',
file: 'dist/index.js',
format: 'umd',
},
plugins: pluginOptions,
}];

View File

@ -1,17 +1,16 @@
var nock = require('nock'); import chai from 'chai'
var chai = require('chai'); import MgBotApiClient from '../index'
var RetailcrmBotApiClient = require('../index');
describe('#Constructor', function () { describe('#Constructor', function () {
it('Empty url', function () { it('Empty url', function () {
chai.expect(function() { chai.expect(function() {
new RetailcrmBotApiClient({token: 'test_token'}); new MgBotApiClient({token: 'test_token'});
}).to.throw('Url is required'); }).to.throw('Url is required');
}); });
it('Incorrect url', function () { it('Incorrect url', function () {
chai.expect(function() { chai.expect(function() {
new RetailcrmBotApiClient({ new MgBotApiClient({
host: 'http://api.example.com', host: 'http://api.example.com',
token: 'test_token' token: 'test_token'
}); });
@ -20,7 +19,7 @@ describe('#Constructor', function () {
it('Empty token', function () { it('Empty token', function () {
chai.expect(function() { chai.expect(function() {
new RetailcrmBotApiClient({host: 'https://api.example.com'}); new MgBotApiClient({host: 'https://api.example.com'});
}).to.throw('Token is required'); }).to.throw('Token is required');
}); });
}); });

View File

@ -1,8 +1,8 @@
var chai = require('chai'); import chai from 'chai'
var request = require('../lib/request'); import Request from '../lib/request'
describe('#Request', function () { describe('#Request', function () {
var req = new request.Request({ let req = new Request({
host: 'http://api.example.com', host: 'http://api.example.com',
token: 'test_token' token: 'test_token'
}); });

View File

@ -1,16 +1,16 @@
var nock = require('nock'); import nock from 'nock'
var chai = require('chai'); import chai from 'chai'
var RetailcrmBotApiClient = require('../index'); import MgBotApiClient from '../index'
describe('#API client v1', function() { describe('#API client v1', function() {
beforeEach(function() { beforeEach(function() {
nock.cleanAll(); nock.cleanAll();
}); });
var retailcrm = new RetailcrmBotApiClient({ const api = new MgBotApiClient({
host: 'https://api.example.com', host: 'https://api.example.com',
token: 'test_token' token: 'test_token'
}).getClient(); }).client;
it('Get bots list', function() { it('Get bots list', function() {
nock('https://api.example.com/api/bot/v1').get('/bots').reply(200, [{ nock('https://api.example.com/api/bot/v1').get('/bots').reply(200, [{
@ -18,7 +18,7 @@ describe('#API client v1', function() {
isActive: true isActive: true
}]); }]);
retailcrm.getBots().then(function (value) { api.getBots().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -27,7 +27,7 @@ describe('#API client v1', function() {
it('Get empty bots list', function () { it('Get empty bots list', function () {
nock('https://api.example.com/api/bot/v1').get('/bots').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/bots').reply(200, []);
retailcrm.getBots().then(function (value) { api.getBots().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -38,7 +38,7 @@ describe('#API client v1', function() {
id: 1 id: 1
}]); }]);
retailcrm.getChannels().then(function (value) { api.getChannels().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -47,7 +47,7 @@ describe('#API client v1', function() {
it('Get empty channels list', function () { it('Get empty channels list', function () {
nock('https://api.example.com/api/bot/v1').get('/channels').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/channels').reply(200, []);
retailcrm.getChannels().then(function (value) { api.getChannels().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -59,7 +59,7 @@ describe('#API client v1', function() {
id: 1 id: 1
}]); }]);
retailcrm.getChats().then(function (value) { api.getChats().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -68,7 +68,7 @@ describe('#API client v1', function() {
it('Get empty chats list', function () { it('Get empty chats list', function () {
nock('https://api.example.com/api/bot/v1').get('/chats').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/chats').reply(200, []);
retailcrm.getChats().then(function (value) { api.getChats().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -81,7 +81,7 @@ describe('#API client v1', function() {
id: 1 id: 1
}]); }]);
retailcrm.getCustomers().then(function (value) { api.getCustomers().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -90,7 +90,7 @@ describe('#API client v1', function() {
it('Get empty customers list', function () { it('Get empty customers list', function () {
nock('https://api.example.com/api/bot/v1').get('/customers').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/customers').reply(200, []);
retailcrm.getCustomers().then(function (value) { api.getCustomers().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -102,7 +102,7 @@ describe('#API client v1', function() {
id: 1 id: 1
}]); }]);
retailcrm.getDialogs().then(function (value) { api.getDialogs().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -111,7 +111,7 @@ describe('#API client v1', function() {
it('Get empty dialogs list', function () { it('Get empty dialogs list', function () {
nock('https://api.example.com/api/bot/v1').get('/dialogs').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/dialogs').reply(200, []);
retailcrm.getDialogs().then(function (value) { api.getDialogs().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -122,7 +122,7 @@ describe('#API client v1', function() {
id: 1 id: 1
}]); }]);
retailcrm.getMembers().then(function (value) { api.getMembers().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -131,7 +131,7 @@ describe('#API client v1', function() {
it('Get empty members list', function () { it('Get empty members list', function () {
nock('https://api.example.com/api/bot/v1').get('/members').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/members').reply(200, []);
retailcrm.getMembers().then(function (value) { api.getMembers().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -145,7 +145,7 @@ describe('#API client v1', function() {
} }
}); });
retailcrm.assignDialog(1, { api.assignDialog(1, {
manager_id: 1 manager_id: 1
}).then(function (value) { }).then(function (value) {
chai.expect(value).to.be.an('object'); chai.expect(value).to.be.an('object');
@ -153,19 +153,19 @@ describe('#API client v1', function() {
}); });
it('Assign dialog incorrect', function () { it('Assign dialog incorrect', function () {
chai.expect(retailcrm.assignDialog.bind(retailcrm)).to.throw('Body is not be empty'); chai.expect(api.assignDialog.bind(api)).to.throw('Parameter `dialog_id` is required');
}); });
it('Close dialog', function () { it('Close dialog', function () {
nock('https://api.example.com/api/bot/v1').delete('/dialogs/1/close').reply(200, {}); nock('https://api.example.com/api/bot/v1').delete('/dialogs/1/close').reply(200, {});
retailcrm.closeDialog(1).then(function (value) { api.closeDialog(1).then(function (value) {
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
}); });
it('Close dialog incorrect', function () { it('Close dialog incorrect', function () {
chai.expect(retailcrm.closeDialog.bind(retailcrm)).to.throw('dialog_id is required'); chai.expect(api.closeDialog.bind(api)).to.throw('Parameter `dialog_id` is required');
}); });
it('Send message', function () { it('Send message', function () {
@ -178,7 +178,7 @@ describe('#API client v1', function() {
message_id: 1 message_id: 1
}); });
retailcrm.sendMessage({ api.sendMessage({
chat_id: 1, chat_id: 1,
scope: 'public', scope: 'public',
type: 'text', type: 'text',
@ -190,7 +190,7 @@ describe('#API client v1', function() {
}); });
it('Send message incorrect', function () { it('Send message incorrect', function () {
chai.expect(retailcrm.sendMessage.bind(retailcrm)).to.throw('Body is not be empty'); chai.expect(api.sendMessage.bind(api)).to.throw('Body is not be empty');
}); });
it('Get messages', function() { it('Get messages', function() {
@ -202,7 +202,7 @@ describe('#API client v1', function() {
} }
}]); }]);
retailcrm.getMessages().then(function (value) { api.getMessages().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -211,7 +211,7 @@ describe('#API client v1', function() {
it('Get empty messages', function () { it('Get empty messages', function () {
nock('https://api.example.com/api/bot/v1').get('/messages').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/messages').reply(200, []);
retailcrm.getMessages().then(function (value) { api.getMessages().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -220,13 +220,13 @@ describe('#API client v1', function() {
it('Delete message', function () { it('Delete message', function () {
nock('https://api.example.com/api/bot/v1').delete('/messages/1').reply(200, {}); nock('https://api.example.com/api/bot/v1').delete('/messages/1').reply(200, {});
retailcrm.deleteMessage(1).then(function (value) { api.deleteMessage(1).then(function (value) {
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
}); });
it('Delete message incorrect', function () { it('Delete message incorrect', function () {
chai.expect(retailcrm.deleteMessage.bind(retailcrm)).to.throw('message_id is required'); chai.expect(api.deleteMessage.bind(api)).to.throw('Parameter `message_id` is required');
}); });
it('Edit message', function () { it('Edit message', function () {
@ -234,7 +234,7 @@ describe('#API client v1', function() {
content: 'tests message' content: 'tests message'
}).reply(200, {}); }).reply(200, {});
retailcrm.editMessage(1, { api.editMessage(1, {
content: 'tests message' content: 'tests message'
}).then(function (value) { }).then(function (value) {
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
@ -242,7 +242,7 @@ describe('#API client v1', function() {
}); });
it('Edit message incorrect', function () { it('Edit message incorrect', function () {
chai.expect(retailcrm.editMessage.bind(retailcrm)).to.throw('Body is not be empty'); chai.expect(api.editMessage.bind(api)).to.throw('Parameter `message_id` is required');
}); });
it('Get commands', function () { it('Get commands', function () {
@ -251,7 +251,7 @@ describe('#API client v1', function() {
name: 'Command name' name: 'Command name'
}]); }]);
retailcrm.getCommands().then(function (value) { api.getCommands().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -260,7 +260,7 @@ describe('#API client v1', function() {
it('Get empty commands', function () { it('Get empty commands', function () {
nock('https://api.example.com/api/bot/v1').get('/my/commands').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/my/commands').reply(200, []);
retailcrm.getCommands().then(function (value) { api.getCommands().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
@ -272,7 +272,7 @@ describe('#API client v1', function() {
name: 'name' name: 'name'
}).reply(200, {}); }).reply(200, {});
retailcrm.editCommand('command', { api.editCommand('command', {
description: 'Desc', description: 'Desc',
name: 'name' name: 'name'
}).then(function (value) { }).then(function (value) {
@ -281,20 +281,20 @@ describe('#API client v1', function() {
}); });
it('Edit command incorrect', function () { it('Edit command incorrect', function () {
chai.expect(retailcrm.editCommand.bind(retailcrm, 'command')).to.throw('Body is not be empty'); chai.expect(api.editCommand.bind(api, 'command')).to.throw('Body is not be empty');
chai.expect(retailcrm.editCommand.bind(retailcrm)).to.throw('Parameter command name is required'); chai.expect(api.editCommand.bind(api)).to.throw('Parameter `command_name` is required');
}); });
it('Delete command', function () { it('Delete command', function () {
nock('https://api.example.com/api/bot/v1').delete('/my/commands/command').reply(200, {}); nock('https://api.example.com/api/bot/v1').delete('/my/commands/command').reply(200, {});
retailcrm.deleteCommand('command').then(function (value) { api.deleteCommand('command').then(function (value) {
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
}); });
it('Delete command incorrect', function () { it('Delete command incorrect', function () {
chai.expect(retailcrm.deleteCommand.bind(retailcrm)).to.throw('command_name is required'); chai.expect(api.deleteCommand.bind(api)).to.throw('Parameter `command_name` is required');
}); });
it('Update bot info', function () { it('Update bot info', function () {
@ -303,7 +303,7 @@ describe('#API client v1', function() {
name: 'Bot' name: 'Bot'
}).reply(200, {}); }).reply(200, {});
retailcrm.info({ api.info({
avatar_url: 'http://tests.ru/avatar.png', avatar_url: 'http://tests.ru/avatar.png',
name: 'Bot' name: 'Bot'
}).then(function (value) { }).then(function (value) {
@ -312,7 +312,7 @@ describe('#API client v1', function() {
}); });
it('Update bot info incorrect', function () { it('Update bot info incorrect', function () {
chai.expect(retailcrm.info.bind(retailcrm)).to.throw('Body is not be empty'); chai.expect(api.info.bind(api)).to.throw('Body is not be empty');
}); });
it('Get users', function () { it('Get users', function () {
@ -321,7 +321,7 @@ describe('#API client v1', function() {
name: 'Username' name: 'Username'
}]); }]);
retailcrm.getUsers().then(function (value) { api.getUsers().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.not.empty; chai.expect(value).to.be.not.empty;
}); });
@ -330,20 +330,22 @@ describe('#API client v1', function() {
it('Get empty users', function () { it('Get empty users', function () {
nock('https://api.example.com/api/bot/v1').get('/users').reply(200, []); nock('https://api.example.com/api/bot/v1').get('/users').reply(200, []);
retailcrm.getUsers().then(function (value) { api.getUsers().then(function (value) {
chai.expect(value).to.be.an('array'); chai.expect(value).to.be.an('array');
chai.expect(value).to.be.empty; chai.expect(value).to.be.empty;
}); });
}); });
it('Get websocket url', function () { it('Get websocket data', function () {
var url = retailcrm.getWebsocketUrl(['message_new', 'message_updated']); const wsData = api.getWebsocketData([MgBotApiClient.types().wsMessageNew, MgBotApiClient.types().wsMessageUpdated]);
var expected = 'wss://api.example.com/api/bot/v1/ws?events=message_new,message_updated'; const expectedUrl = 'wss://api.example.com/api/bot/v1/ws?events=message_new,message_updated';
const expectedHeaders = {'X-Bot-Token': 'test_token'};
chai.assert.equal(url, expected); chai.assert.equal(wsData.get('url'), expectedUrl);
chai.assert.equal(wsData.get('headers')["X-Bot-Token"], expectedHeaders["X-Bot-Token"]);
}); });
it('Get websocket url incorrect', function () { it('Get websocket url incorrect', function () {
chai.expect(retailcrm.getWebsocketUrl.bind(retailcrm)).to.throw('Events is required'); chai.expect(api.getWebsocketData.bind(api)).to.throw('Events is required');
}); });
}); });