You're Invited: Meet the Socket team at BSidesSF and RSAC - April 27 - May 1.RSVP
Socket
Sign inDemoInstall
Socket

messaging-api-slack

Package Overview
Dependencies
Maintainers
3
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

messaging-api-slack - npm Package Compare versions

Comparing version

to
0.7.0-beta.1

src/__tests__/SlackOAuthClient-constructor.spec.js

413

lib/SlackOAuthClient.js

@@ -62,3 +62,9 @@ 'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;};

class SlackOAuthClient {
static connect(accessTokenOrConfig) {
return new SlackOAuthClient(accessTokenOrConfig);
}

@@ -69,9 +75,18 @@

constructor(accessTokenOrConfig) {
let origin;
if (accessTokenOrConfig && typeof accessTokenOrConfig === 'object') {
const config = accessTokenOrConfig;
this._token = config.accessToken;
origin = config.origin;
} else {
// Bot User OAuth Access Token
this._token = accessTokenOrConfig;
}
constructor(token) {_initialiseProps.call(this);
// Web API
// https://api.slack.com/web
this._axios = _axios2.default.create({
baseURL: 'https://slack.com/api/',
baseURL: `${origin || 'https://slack.com'}/api/`,
headers: {

@@ -81,4 +96,2 @@ 'Content-Type': 'application/x-www-form-urlencoded' } });

// Bot User OAuth Access Token
this._token = token;
}

@@ -94,25 +107,25 @@

callMethod(
method,
body = {})
{var _this = this;return _asyncToGenerator(function* () {
body.token = body.token || _this._token; // eslint-disable-line no-param-reassign
const response = yield _this._axios.post(
method,
_querystring2.default.stringify(body));const
data = response.data,config = response.config,request = response.request;
if (!data.ok) {
throw new _axiosError2.default(`Slack API - ${data.error}`, {
config,
request,
response });
}
return data;})();
}
/**

@@ -123,44 +136,63 @@ * Gets information about a public channel.

*/
getChannelInfo(
channelId,
options = {})
{
return this.callMethod('channels.info', _extends({
channel: channelId },
options)).
then(data => data.channel);
}
/**
* Lists all public channels in a Slack team.
*
* https://api.slack.com/methods/channels.list
* FIXME: [breaking] support cursor, exclude_archived, exclude_members, limit
*/
* Lists all public channels in a Slack team.
*
* https://api.slack.com/methods/channels.list
* FIXME: [breaking] support cursor, exclude_archived, exclude_members, limit
*/
getChannelList() {
return this.callMethod('channels.list').then(data => data.channels);
}
/**
* Retrieve information about a conversation.
*
* https://api.slack.com/methods/conversations.info
*/
* Retrieve information about a conversation.
*
* https://api.slack.com/methods/conversations.info
*/
getConversationInfo(
channelId,
options = {})
{
return this.callMethod('conversations.info', _extends({
channel: channelId },
options)).
then(data => data.channel);
}
/**
* Retrieve members of a conversation.
*
* https://api.slack.com/methods/conversations.members
*/
* Retrieve members of a conversation.
*
* https://api.slack.com/methods/conversations.members
*/
getConversationMembers(
channelId,
options = {})
{
return this.callMethod('conversations.members', _extends({
channel: channelId },
options)).
then(data => ({
members: data.members,
next: data.response_metadata && data.response_metadata.next_cursor }));
}
getAllConversationMembers(channelId) {var _this2 = this;return _asyncToGenerator(function* () {
let allMembers = [];
let continuationCursor;
do {var _ref =

@@ -170,11 +202,36 @@

yield _this2.getConversationMembers(channelId, {
cursor: continuationCursor });const members = _ref.members,next = _ref.next;
allMembers = allMembers.concat(members);
continuationCursor = next;
} while (continuationCursor);
return allMembers;})();
}
/**
* Lists all channels in a Slack team.
*
* https://api.slack.com/methods/conversations.list
*/
getConversationList(
options = {})
{
return this.callMethod('conversations.list', options).then(data => ({
channels: data.channels,
next: data.response_metadata && data.response_metadata.next_cursor }));
}
getAllConversationList(
options = {})
{var _this3 = this;return _asyncToGenerator(function* () {
let allChannels = [];
let continuationCursor;
do {var _ref2 =

@@ -184,142 +241,128 @@

yield _this3.getConversationList(_extends({},
options, {
cursor: continuationCursor }));const channels = _ref2.channels,next = _ref2.next;
allChannels = allChannels.concat(channels);
continuationCursor = next;
} while (continuationCursor);
return allChannels;})();
}
/**
* Lists all channels in a Slack team.
*
* https://api.slack.com/methods/conversations.list
*/
* Sends a message to a channel.
*
* https://api.slack.com/methods/chat.postMessage
*/
postMessage(
channel,
message,
options = {})
{
if (options.attachments && typeof options.attachments !== 'string') {
// A JSON-based array of structured attachments, presented as a URL-encoded string.
// eslint-disable-next-line no-param-reassign
options.attachments = JSON.stringify(options.attachments);
} else if (
typeof message === 'object' &&
message.attachments &&
typeof message.attachments !== 'string')
{
// eslint-disable-next-line no-param-reassign
message.attachments = JSON.stringify(message.attachments);
}
if (typeof message === 'string') {
return this.callMethod('chat.postMessage', _extends({
channel,
text: message },
options));
}
return this.callMethod('chat.postMessage', _extends({
channel },
message,
options));
}
/**
* Sends a message to a channel.
*
* https://api.slack.com/methods/chat.postMessage
*/
* Sends an ephemeral message to a user in a channel.
*
* https://api.slack.com/methods/chat.postMessage
*/
postEphemeral(
channel,
user,
message,
options = {})
{
if (options.attachments && typeof options.attachments !== 'string') {
// A JSON-based array of structured attachments, presented as a URL-encoded string.
// eslint-disable-next-line no-param-reassign
options.attachments = JSON.stringify(options.attachments);
} else if (
typeof message === 'object' &&
message.attachments &&
typeof message.attachments !== 'string')
{
// eslint-disable-next-line no-param-reassign
message.attachments = JSON.stringify(message.attachments);
}
if (typeof message === 'string') {
return this.callMethod('chat.postEphemeral', _extends({
channel,
user,
text: message },
options));
}
return this.callMethod('chat.postEphemeral', _extends({
channel,
user },
message,
options));
}
/**
* Sends an ephemeral message to a user in a channel.
*
* https://api.slack.com/methods/chat.postMessage
*/
* Gets information about a user.
*
* https://api.slack.com/methods/users.info
*/
getUserInfo(
userId,
options = {})
{
return this.callMethod('users.info', _extends({ user: userId }, options)).then(
data => data.user);
}
/**
* Gets information about a user.
*
* https://api.slack.com/methods/users.info
*/
* Lists all users in a Slack team.
*
* https://api.slack.com/methods/users.list
* FIXME: [breaking] support include_locale, limit, presence
*/
getUserList(
cursor)
{
return this.callMethod('users.list', { cursor }).then(data => ({
members: data.members,
next: data.response_metadata && data.response_metadata.next_cursor }));
}
getAllUserList() {var _this4 = this;return _asyncToGenerator(function* () {
let allUsers = [];
let continuationCursor;
do {var _ref3 =

@@ -329,32 +372,8 @@

yield _this4.getUserList(continuationCursor);const users = _ref3.members,next = _ref3.next;
allUsers = allUsers.concat(users);
continuationCursor = next;
} while (continuationCursor);
/**
* Lists all users in a Slack team.
*
* https://api.slack.com/methods/users.list
* FIXME: [breaking] support include_locale, limit, presence
*/}exports.default = SlackOAuthClient;SlackOAuthClient.connect = token => new SlackOAuthClient(token);var _initialiseProps = function _initialiseProps() {var _this = this;this.callMethod = (() => {var _ref = _asyncToGenerator(function* (method, body = {}) {body.token = body.token || _this._token; // eslint-disable-line no-param-reassign
const response = yield _this._axios.post(method, _querystring2.default.stringify(body));const data = response.data,config = response.config,request = response.request;if (!data.ok) {throw new _axiosError2.default(`Slack API - ${data.error}`, { config, request, response });}return data;});return function (_x) {return _ref.apply(this, arguments);};})();this.getChannelInfo = (channelId, options = {}) => this.callMethod('channels.info', _extends({ channel: channelId }, options)).then(data => data.channel);this.getChannelList = () => this.callMethod('channels.list').then(data => data.channels);this.getConversationInfo = (channelId, options = {}) => this.callMethod('conversations.info', _extends({ channel: channelId }, options)).then(data => data.channel);this.getConversationMembers = (channelId, options = {}) => this.callMethod('conversations.members', _extends({ channel: channelId }, options)).then(data => ({ members: data.members, next: data.response_metadata && data.response_metadata.next_cursor }));this.getAllConversationMembers = (() => {var _ref2 = _asyncToGenerator(function* (channelId) {let allMembers = [];let continuationCursor;do {var _ref3 = yield _this.getConversationMembers(channelId, { cursor: continuationCursor });const members = _ref3.members,next = _ref3.next;allMembers = allMembers.concat(members);continuationCursor = next;} while (continuationCursor);return allMembers;});return function (_x2) {return _ref2.apply(this, arguments);};})();this.getConversationList = (options = {}) => this.callMethod('conversations.list', options).then(data => ({ channels: data.channels, next: data.response_metadata && data.response_metadata.next_cursor }));this.getAllConversationList = (() => {var _ref4 = _asyncToGenerator(function* (options = {}) {let allChannels = [];let continuationCursor;do {var _ref5 = yield _this.getConversationList(_extends({}, options, { cursor: continuationCursor }));const channels = _ref5.channels,next = _ref5.next;allChannels = allChannels.concat(channels);continuationCursor = next;} while (continuationCursor);return allChannels;});return function () {return _ref4.apply(this, arguments);};})();this.postMessage = (channel, message, options = {}) => {if (options.attachments && typeof options.attachments !== 'string') {// A JSON-based array of structured attachments, presented as a URL-encoded string.
// eslint-disable-next-line no-param-reassign
options.attachments = JSON.stringify(options.attachments);} else if (typeof message === 'object' && message.attachments && typeof message.attachments !== 'string') {// eslint-disable-next-line no-param-reassign
message.attachments = JSON.stringify(message.attachments);}if (typeof message === 'string') {return this.callMethod('chat.postMessage', _extends({ channel, text: message }, options));}return this.callMethod('chat.postMessage', _extends({ channel }, message, options));};this.postEphemeral = (channel, user, message, options = {}) => {if (options.attachments && typeof options.attachments !== 'string') {// A JSON-based array of structured attachments, presented as a URL-encoded string.
// eslint-disable-next-line no-param-reassign
options.attachments = JSON.stringify(options.attachments);} else if (typeof message === 'object' && message.attachments && typeof message.attachments !== 'string') {// eslint-disable-next-line no-param-reassign
message.attachments = JSON.stringify(message.attachments);}if (typeof message === 'string') {return this.callMethod('chat.postEphemeral', _extends({ channel, user, text: message }, options));}return this.callMethod('chat.postEphemeral', _extends({ channel, user }, message, options));};this.getUserInfo = (userId, options = {}) => this.callMethod('users.info', _extends({ user: userId }, options)).then(data => data.user);this.getUserList = cursor => this.callMethod('users.list', { cursor }).then(data => ({ members: data.members, next: data.response_metadata && data.response_metadata.next_cursor }));this.
getAllUserList = _asyncToGenerator(function* () {
let allUsers = [];
let continuationCursor;
do {var _ref7 =
yield _this.getUserList(continuationCursor);const users = _ref7.members,next = _ref7.next;
allUsers = allUsers.concat(users);
continuationCursor = next;
} while (continuationCursor);
return allUsers;
});};
return allUsers;})();
}}exports.default = SlackOAuthClient;

@@ -18,8 +18,9 @@ 'use strict';Object.defineProperty(exports, "__esModule", { value: true });

class SlackWebhookClient {
static connect(url) {
return new SlackWebhookClient(url);
}
constructor(url) {_initialiseProps.call(this);
constructor(url) {
// incoming webhooks

@@ -37,8 +38,10 @@ // https://api.slack.com/incoming-webhooks

sendRawBody(body) {
return this._axios.post('', body).then(res => res.data);
}
sendText(text) {
return this.sendRawBody({ text });
}
/**

@@ -48,10 +51,14 @@ * Attachments

* https://api.slack.com/docs/message-attachments
*/}exports.default = SlackWebhookClient;SlackWebhookClient.connect = url => new SlackWebhookClient(url);var _initialiseProps = function _initialiseProps() {this.sendRawBody = body => this._axios.post('', body).then(res => res.data);this.sendText = text => this.sendRawBody({ text });this.
*/
sendAttachments =
attachments =>
this.sendRawBody({ attachments });this.
sendAttachments(
attachments)
{
return this.sendRawBody({ attachments });
}
sendAttachment =
attachment =>
this.sendAttachments([attachment]);};
sendAttachment(
attachment)
{
return this.sendAttachments([attachment]);
}}exports.default = SlackWebhookClient;
{
"name": "messaging-api-slack",
"description": "Messaging API client for Slack",
"version": "0.7.0-alpha.2",
"version": "0.7.0-beta.1",
"engines": {

@@ -22,3 +22,3 @@ "node": ">=6"

"axios": "^0.17.0",
"axios-error": "^0.7.0-alpha.2"
"axios-error": "^0.7.0-beta.1"
},

@@ -25,0 +25,0 @@ "devDependencies": {

@@ -9,9 +9,10 @@ # messaging-api-slack

- [Installation](#installation)
- [OAuth Client](#oauth-client)
- [Usage](#usage)
- [API Reference](#api-reference)
- [Webhook Client](#webhook-client)
- [Usage](#usage-1)
- [API Reference](#api-reference-1)
* [Installation](#installation)
* [OAuth Client](#oauth-client)
* [Usage](#usage)
* [API Reference](#api-reference)
* [Test](#test)
* [Webhook Client](#webhook-client)
* [Usage](#usage-1)
* [API Reference](#api-reference-1)

@@ -23,3 +24,5 @@ ## Installation

```
or
```sh

@@ -61,8 +64,9 @@ yarn add messaging-api-slack

Param | Type | Description
------ | -------- | -----------
method | `String` | One of [API Methods](https://api.slack.com/methods)
body | `Object` | Body that the method needs.
| Param | Type | Description |
| ------ | -------- | --------------------------------------------------- |
| method | `String` | One of [API Methods](https://api.slack.com/methods) |
| body | `Object` | Body that the method needs. |
Example:
```js

@@ -80,9 +84,10 @@ client.callMethod('chat.postMessage', { channel: 'C8763', text: 'Hello!' });

Param | Type | Description
------- | --------------------------------- | -----------
channel | `String` | Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name.
message | <code>String &#124; Object</code> | The message to be sent, can be text message or attachment message.
options | `Object` | Other optional parameters.
| Param | Type | Description |
| ------- | --------------------------------- | ------------------------------------------------------------------------------------------ |
| channel | `String` | Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name. |
| message | <code>String &#124; Object</code> | The message to be sent, can be text message or attachment message. |
| options | `Object` | Other optional parameters. |
Example:
```js

@@ -96,2 +101,3 @@ client.postMessage('C8763', { text: 'Hello!' });

If you send message with `attachments`, `messaging-api-slack` will automatically stringify the `attachments` field for you.
```js

@@ -132,10 +138,11 @@ client.postMessage(

Param | Type | Description
------- | --------------------------------- | -----------
channel | `String` | Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name.
user | `String` | `id` of the user who will receive the ephemeral message. The user should be in the channel specified by the `channel` argument.
message | <code>String &#124; Object</code> | The message to be sent, can be text message or attachment message.
options | `Object` | Other optional parameters.
| Param | Type | Description |
| ------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| channel | `String` | Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name. |
| user | `String` | `id` of the user who will receive the ephemeral message. The user should be in the channel specified by the `channel` argument. |
| message | <code>String &#124; Object</code> | The message to be sent, can be text message or attachment message. |
| options | `Object` | Other optional parameters. |
Example:
```js

@@ -156,7 +163,8 @@ client.postEphemeral('C8763', 'U56781234', { text: 'Hello!' });

Param | Type | Description
------ | -------- | -----------
cursor | `String` | Paginate through collections of data by setting the `cursor` parameter to a `next_cursor` attribute returned by a previous request's `response_metadata`.
| Param | Type | Description |
| ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| cursor | `String` | Paginate through collections of data by setting the `cursor` parameter to a `next_cursor` attribute returned by a previous request's `response_metadata`. |
Example:
```js

@@ -182,2 +190,3 @@ client.getUserList(cursor).then(res => {

Example:
```js

@@ -199,7 +208,8 @@ client.getAllUserList().then(res => {

Param | Type | Description
------ | -------- | -----------
userId | `String` | User to get info on.
| Param | Type | Description |
| ------ | -------- | -------------------- |
| userId | `String` | User to get info on. |
Example:
```js

@@ -225,2 +235,3 @@ client.getUserInfo(userId).then(res => {

Example:
```js

@@ -242,7 +253,8 @@ client.getChannelList().then(res => {

Param | Type | Description
--------- | -------- | -----------
channelId | `String` | Channel to get info on.
| Param | Type | Description |
| --------- | -------- | ----------------------- |
| channelId | `String` | Channel to get info on. |
Example:
```js

@@ -267,7 +279,8 @@ client.getChannelInfo(channelId).then(res => {

Param | Type | Description
--------- | -------- | -----------
channelId | `String` | Channel to get info on.
| Param | Type | Description |
| --------- | -------- | ----------------------- |
| channelId | `String` | Channel to get info on. |
Example:
```js

@@ -290,8 +303,9 @@ client.getConversationInfo(channelId).then(res => {

Param | Type | Description
--------- | -------- | -----------
channelId | `String` | Channel to get info on.
options | `Object` | Optional arguments.
| Param | Type | Description |
| --------- | -------- | ----------------------- |
| channelId | `String` | Channel to get info on. |
| options | `Object` | Optional arguments. |
Example:
```js

@@ -314,7 +328,8 @@ client.getConversationMembers(channelId, { cursor: 'xxx' });

Param | Type | Description
--------- | -------- | -----------
channelId | `String` | Channel to get info on.
| Param | Type | Description |
| --------- | -------- | ----------------------- |
| channelId | `String` | Channel to get info on. |
Example:
```js

@@ -333,7 +348,8 @@ client.getAllConversationMembers(channelId).then(res => {

Param | Type | Description
--------- | -------- | -----------
options | `Object` | Optional arguments.
| Param | Type | Description |
| ------- | -------- | ------------------- |
| options | `Object` | Optional arguments. |
Example:
```js

@@ -367,7 +383,8 @@ client.getConversationList({ cursor: 'xxx' });

Param | Type | Description
--------- | -------- | -----------
options | `Object` | Optional arguments.
| Param | Type | Description |
| ------- | -------- | ------------------- |
| options | `Object` | Optional arguments. |
Example:
```js

@@ -393,2 +410,21 @@ client.getAllConversationList().then(res => {

## Test
### Point requests to your dummy server
To avoid sending requests to real Slack server, specify `origin` option when constructing your client:
```js
const { SlackOAuthClient } = require('messaging-api-slack');
const client = SlackOAuthClient.connect({
accessToken: ACCESS_TOKEN,
origin: 'https://mydummytestserver.com',
});
```
> Warning: Don't do this on production server.
<br />
## Webhook Client

@@ -422,7 +458,8 @@

Param | Type | Description
----- | -------- | -----------
body | `Object` | Raw data to be sent.
| Param | Type | Description |
| ----- | -------- | -------------------- |
| body | `Object` | Raw data to be sent. |
Example:
```js

@@ -436,7 +473,8 @@ client.sendRawBody({ text: 'Hello!' });

Param | Type | Description
----- | -------- | -----------
text | `String` | Text of the message to be sent.
| Param | Type | Description |
| ----- | -------- | ------------------------------- |
| text | `String` | Text of the message to be sent. |
Example:
```js

@@ -452,7 +490,8 @@ client.sendText('Hello!');

Param | Type | Description
----------- | --------------- | -----------
attachments | `Array<Object>` | Messages are attachments, defined as an array. Each object contains the parameters to customize the appearance of a message attachment.
| Param | Type | Description |
| ----------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| attachments | `Array<Object>` | Messages are attachments, defined as an array. Each object contains the parameters to customize the appearance of a message attachment. |
Example:
```js

@@ -493,7 +532,8 @@ client.sendAttachments([

Param | Type | Description
----------- | -------- | -----------
attachments | `Object` | Message is an attachment. The object contains the parameters to customize the appearance of a message attachment.
| Param | Type | Description |
| ----------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| attachments | `Object` | Message is an attachment. The object contains the parameters to customize the appearance of a message attachment. |
Example:
```js

@@ -500,0 +540,0 @@ client.sendAttachment({

@@ -17,66 +17,2 @@ import querystring from 'querystring';

describe('connect', () => {
let axios;
let _create;
beforeEach(() => {
axios = require('axios'); // eslint-disable-line global-require
_create = axios.create;
});
afterEach(() => {
axios.create = _create;
});
it('create axios with slack api url', () => {
axios.create = jest.fn();
SlackOAuthClient.connect(TOKEN);
expect(axios.create).toBeCalledWith({
baseURL: 'https://slack.com/api/',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
});
});
describe('constructor', () => {
let axios;
let _create;
beforeEach(() => {
axios = require('axios'); // eslint-disable-line global-require
_create = axios.create;
});
afterEach(() => {
axios.create = _create;
});
it('create axios with with slack api url', () => {
axios.create = jest.fn();
new SlackOAuthClient(TOKEN); // eslint-disable-line no-new
expect(axios.create).toBeCalledWith({
baseURL: 'https://slack.com/api/',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
});
});
describe('#axios', () => {
it('should return underlying http client', () => {
const client = new SlackOAuthClient(TOKEN);
const http = client.axios;
expect(http.get).toBeDefined();
expect(http.post).toBeDefined();
expect(http.put).toBeDefined();
expect(http.delete).toBeDefined();
});
});
describe('#accessToken', () => {
it('should return underlying access token', () => {
const client = new SlackOAuthClient(TOKEN);
expect(client.accessToken).toBe(TOKEN);
});
});
describe('#callMethod', () => {

@@ -83,0 +19,0 @@ it('should call slack api', async () => {

@@ -13,58 +13,2 @@ import MockAdapter from 'axios-mock-adapter';

describe('connect', () => {
let axios;
let _create;
beforeEach(() => {
axios = require('axios'); // eslint-disable-line global-require
_create = axios.create;
});
afterEach(() => {
axios.create = _create;
});
it('create axios with webhook url', () => {
axios.create = jest.fn();
SlackWebhookClient.connect(URL);
expect(axios.create).toBeCalledWith({
baseURL: 'https://hooks.slack.com/services/XXXXXXXX/YYYYYYYY/zzzzzZZZZZ',
headers: { 'Content-Type': 'application/json' },
});
});
});
describe('constructor', () => {
let axios;
let _create;
beforeEach(() => {
axios = require('axios'); // eslint-disable-line global-require
_create = axios.create;
});
afterEach(() => {
axios.create = _create;
});
it('create axios with with webhook url', () => {
axios.create = jest.fn();
new SlackWebhookClient(URL); // eslint-disable-line no-new
expect(axios.create).toBeCalledWith({
baseURL: 'https://hooks.slack.com/services/XXXXXXXX/YYYYYYYY/zzzzzZZZZZ',
headers: { 'Content-Type': 'application/json' },
});
});
});
describe('#axios', () => {
it('should return underlying http client', () => {
const client = new SlackWebhookClient(URL);
expect(client.axios.get).toBeDefined();
expect(client.axios.post).toBeDefined();
expect(client.axios.put).toBeDefined();
expect(client.axios.delete).toBeDefined();
});
});
describe('sendRawBody', () => {

@@ -71,0 +15,0 @@ it('should call messages api', async () => {

@@ -24,4 +24,2 @@ /* @flow */

type Token = string;
type PostMessageOptions = {

@@ -63,15 +61,32 @@ as_user?: boolean,

type ClientConfig = {
accessToken: string,
origin?: string,
};
export default class SlackOAuthClient {
static connect = (token: Token): SlackOAuthClient =>
new SlackOAuthClient(token);
static connect(accessTokenOrConfig: string | ClientConfig): SlackOAuthClient {
return new SlackOAuthClient(accessTokenOrConfig);
}
_axios: Axios;
_token: Token;
_token: string;
constructor(token: Token) {
constructor(accessTokenOrConfig: string | ClientConfig) {
let origin;
if (accessTokenOrConfig && typeof accessTokenOrConfig === 'object') {
const config = accessTokenOrConfig;
this._token = config.accessToken;
origin = config.origin;
} else {
// Bot User OAuth Access Token
this._token = accessTokenOrConfig;
}
// Web API
// https://api.slack.com/web
this._axios = axios.create({
baseURL: 'https://slack.com/api/',
baseURL: `${origin || 'https://slack.com'}/api/`,
headers: {

@@ -81,4 +96,2 @@ 'Content-Type': 'application/x-www-form-urlencoded',

});
// Bot User OAuth Access Token
this._token = token;
}

@@ -90,10 +103,10 @@

get accessToken(): Token {
get accessToken(): string {
return this._token;
}
callMethod = async (
async callMethod(
method: SlackAvailableMethod,
body: Object = {}
): Promise<SlackOAuthAPIResponse> => {
): Promise<SlackOAuthAPIResponse> {
body.token = body.token || this._token; // eslint-disable-line no-param-reassign

@@ -116,3 +129,3 @@ const response = await this._axios.post(

return data;
};
}

@@ -124,9 +137,11 @@ /**

*/
getChannelInfo = (
getChannelInfo(
channelId: string,
options: GetInfoOptions = {}
): Promise<SlackChannel> =>
this.callMethod('channels.info', { channel: channelId, ...options }).then(
data => data.channel
);
): Promise<SlackChannel> {
return this.callMethod('channels.info', {
channel: channelId,
...options,
}).then(data => data.channel);
}

@@ -139,4 +154,5 @@ /**

*/
getChannelList = (): Promise<Array<SlackChannel>> =>
this.callMethod('channels.list').then(data => data.channels);
getChannelList(): Promise<Array<SlackChannel>> {
return this.callMethod('channels.list').then(data => data.channels);
}

@@ -148,10 +164,11 @@ /**

*/
getConversationInfo = (
getConversationInfo(
channelId: string,
options: GetInfoOptions = {}
): Promise<SlackChannel> =>
this.callMethod('conversations.info', {
): Promise<SlackChannel> {
return this.callMethod('conversations.info', {
channel: channelId,
...options,
}).then(data => data.channel);
}

@@ -163,3 +180,3 @@ /**

*/
getConversationMembers = (
getConversationMembers(
channelId: string,

@@ -170,4 +187,4 @@ options: WithCursorOptions = {}

next: ?string,
}> =>
this.callMethod('conversations.members', {
}> {
return this.callMethod('conversations.members', {
channel: channelId,

@@ -179,6 +196,5 @@ ...options,

}));
}
getAllConversationMembers = async (
channelId: string
): Promise<Array<string>> => {
async getAllConversationMembers(channelId: string): Promise<Array<string>> {
let allMembers = [];

@@ -200,3 +216,3 @@ let continuationCursor;

return allMembers;
};
}

@@ -208,3 +224,3 @@ /**

*/
getConversationList = (
getConversationList(
options: ConversationListOptions = {}

@@ -214,11 +230,12 @@ ): Promise<{

next: ?string,
}> =>
this.callMethod('conversations.list', options).then(data => ({
}> {
return this.callMethod('conversations.list', options).then(data => ({
channels: data.channels,
next: data.response_metadata && data.response_metadata.next_cursor,
}));
}
getAllConversationList = async (
async getAllConversationList(
options: ConversationListOptions = {}
): Promise<Array<SlackChannel>> => {
): Promise<Array<SlackChannel>> {
let allChannels = [];

@@ -241,3 +258,3 @@ let continuationCursor;

return allChannels;
};
}

@@ -249,3 +266,3 @@ /**

*/
postMessage = (
postMessage(
channel: string,

@@ -256,3 +273,3 @@ message:

options?: PostMessageOptions = {}
): Promise<SlackOAuthAPIResponse> => {
): Promise<SlackOAuthAPIResponse> {
if (options.attachments && typeof options.attachments !== 'string') {

@@ -283,3 +300,3 @@ // A JSON-based array of structured attachments, presented as a URL-encoded string.

});
};
}

@@ -291,3 +308,3 @@ /**

*/
postEphemeral = (
postEphemeral(
channel: string,

@@ -299,3 +316,3 @@ user: string,

options?: postEphemeral = {}
): Promise<SlackOAuthAPIResponse> => {
): Promise<SlackOAuthAPIResponse> {
if (options.attachments && typeof options.attachments !== 'string') {

@@ -328,3 +345,3 @@ // A JSON-based array of structured attachments, presented as a URL-encoded string.

});
};
}

@@ -336,9 +353,10 @@ /**

*/
getUserInfo = (
getUserInfo(
userId: string,
options: GetInfoOptions = {}
): Promise<SlackUser> =>
this.callMethod('users.info', { user: userId, ...options }).then(
): Promise<SlackUser> {
return this.callMethod('users.info', { user: userId, ...options }).then(
data => data.user
);
}

@@ -351,11 +369,12 @@ /**

*/
getUserList = (
getUserList(
cursor?: string
): Promise<{ members: Array<SlackUser>, next: ?string }> =>
this.callMethod('users.list', { cursor }).then(data => ({
): Promise<{ members: Array<SlackUser>, next: ?string }> {
return this.callMethod('users.list', { cursor }).then(data => ({
members: data.members,
next: data.response_metadata && data.response_metadata.next_cursor,
}));
}
getAllUserList = async (): Promise<Array<SlackUser>> => {
async getAllUserList(): Promise<Array<SlackUser>> {
let allUsers = [];

@@ -375,3 +394,3 @@ let continuationCursor;

return allUsers;
};
}
}

@@ -18,4 +18,5 @@ /* @flow */

export default class SlackWebhookClient {
static connect = (url: URL): SlackWebhookClient =>
new SlackWebhookClient(url);
static connect(url: URL): SlackWebhookClient {
return new SlackWebhookClient(url);
}

@@ -37,7 +38,9 @@ _axios: Axios;

sendRawBody = (body: Object): Promise<SendMessageSucessResponse> =>
this._axios.post('', body).then(res => res.data);
sendRawBody(body: Object): Promise<SendMessageSucessResponse> {
return this._axios.post('', body).then(res => res.data);
}
sendText = (text: string): Promise<SendMessageSucessResponse> =>
this.sendRawBody({ text });
sendText(text: string): Promise<SendMessageSucessResponse> {
return this.sendRawBody({ text });
}

@@ -50,9 +53,13 @@ /**

sendAttachments = (
sendAttachments(
attachments: Array<SlackAttachment>
): Promise<SendMessageSucessResponse> => this.sendRawBody({ attachments });
): Promise<SendMessageSucessResponse> {
return this.sendRawBody({ attachments });
}
sendAttachment = (
sendAttachment(
attachment: SlackAttachment
): Promise<SendMessageSucessResponse> => this.sendAttachments([attachment]);
): Promise<SendMessageSucessResponse> {
return this.sendAttachments([attachment]);
}
}