Skip to content

Commit 1c5b484

Browse files
authored
Merge pull request #6 from swellaby/m
feat(messaging): add generic message posting method
2 parents 955036c + 4260300 commit 1c5b484

File tree

4 files changed

+73
-1
lines changed

4 files changed

+73
-1
lines changed

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,6 @@
4646
},
4747
"publishConfig": {
4848
"access": "public"
49-
}
49+
},
50+
"typings": "src/index.ts"
5051
}

src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './models';
2+
export * from './post-message';
23
export * from './slackbot';

src/post-message.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { request } from 'https';
2+
3+
/**
4+
* Posts a message to slack
5+
* @export
6+
* @param {string} message to post
7+
* @param {string} path to post message to
8+
* @param {('ephemeral' | 'in_channel')} [responseType='in_channel']
9+
*/
10+
export function postMessage(message: string, path: string, responseType: 'ephemeral' | 'in_channel' = 'in_channel'): void {
11+
const req = request({
12+
headers: {
13+
'Content-Type': 'application/json'
14+
},
15+
host: 'hooks.slack.com',
16+
path: path,
17+
method: 'POST'
18+
});
19+
req.write(JSON.stringify({
20+
response_type: responseType,
21+
text: message
22+
}));
23+
req.end();
24+
}

test/post-message.test.ts

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import * as https from 'https';
2+
import { postMessage } from '../src';
3+
4+
describe('postMessage', () => {
5+
let writeSpy: jest.Mock;
6+
let endSpy: jest.Mock;
7+
let reqSpy: jest.Mock;
8+
9+
beforeEach(() => {
10+
writeSpy = jest.fn();
11+
endSpy = jest.fn();
12+
reqSpy = jest.spyOn(https, 'request').mockReturnValue({ write: writeSpy, end: endSpy });
13+
});
14+
15+
it('should build request prpoerly', () => {
16+
postMessage('message', 'path');
17+
expect(reqSpy).toHaveBeenCalled();
18+
expect(reqSpy.mock.calls[0][0]).toEqual({
19+
headers: { 'Content-Type': 'application/json' },
20+
host: 'hooks.slack.com',
21+
path: 'path',
22+
method: 'POST'
23+
});
24+
expect(writeSpy).toHaveBeenCalled();
25+
expect(JSON.parse(writeSpy.mock.calls[0][0])).toEqual({
26+
response_type: 'in_channel',
27+
text: 'message'
28+
});
29+
});
30+
31+
it('should except responseType override', () => {
32+
postMessage('message', 'path', 'ephemeral');
33+
expect(reqSpy).toHaveBeenCalled();
34+
expect(reqSpy.mock.calls[0][0]).toEqual({
35+
headers: { 'Content-Type': 'application/json' },
36+
host: 'hooks.slack.com',
37+
path: 'path',
38+
method: 'POST'
39+
});
40+
expect(writeSpy).toHaveBeenCalled();
41+
expect(JSON.parse(writeSpy.mock.calls[0][0])).toEqual({
42+
response_type: 'ephemeral',
43+
text: 'message'
44+
});
45+
});
46+
});

0 commit comments

Comments
 (0)