-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
96 lines (80 loc) · 1.84 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env node
const io = require('socket.io-client');
const config = require('./config');
const events = require('events');
const axios = require('axios');
const store = { apiKey: '' };
const setApiKey = (apiKey) => {
store.apiKey = apiKey;
};
/*
* Query API
*/
/**
* Query news
*
* @param {String} query The query string
* @returns {Object} The response from the API
*/
const getNews = async (query = {}) => {
const payload = { ...query, type: 'filterArticles' };
const options = {
method: 'post',
url: config.queryApi.endpoint,
headers: { Authorization: store.apiKey },
data: payload,
};
let { data } = await axios(options);
data.articles = data.articles.map(
({ markets, categories, content, meta, ...rest }) => ({
...rest,
})
);
return data;
};
/*
* Stream API
*/
const streamApiStore = {};
const initSocket = (apiKey) => {
const uri = config.streamApi.endpoint;
const params = { query: { apiKey } };
streamApiStore.socket = io(uri, params);
streamApiStore.socket.on('connect', () =>
console.log('Socket connected to', uri)
);
streamApiStore.socket.on('articles', handleNewArticles);
streamApiStore.socket.on('error', console.error);
};
const handleNewArticles = (articles) => {
console.log(articles);
streamApiStore.eventEmitter.emit('articles', articles);
};
const close = () => {
if (streamApiStore.socket.close) {
streamApiStore.socket.close();
}
};
const connect = (apiKey) => {
setApiKey(apiKey);
initSocket(apiKey);
streamApiStore.eventEmitter = new events.EventEmitter();
modules.streamApi.on = streamApiStore.eventEmitter.on;
return streamApiStore.eventEmitter;
};
/**
* Exports
*/
const modules = {
setApiKey,
queryApi: {
setApiKey,
getNews,
},
streamApi: {
setApiKey,
connect,
close,
},
};
module.exports = modules;