This repository has been archived by the owner on Jan 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.js
80 lines (68 loc) · 2.04 KB
/
model.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
var config = require('./config');
var model = module.exports = {};
var request = require('request');
model.UNAUTHENTICATED_ERR = {
code: 'NOT_AUTHENTICATED',
name: 'UnauthenticatedError',
message: 'Not authenticated',
status: 401,
user_message: 'You are not authenticated'
};
model.formatMessage = function (message) {
if (!message || !message.id) return null;
message.timestamp = model._formatTimestamp(message.timestamp);
return message;
};
model.getTopicsByIds = function (topic_ids, callback) {
request({
baseUrl: config.api.baseUrl,
json: true,
timeout: 5000,
url: '/v1/topics',
headers: {
'User-Agent': config.api.user_agent
},
qs: {
fields: 'id,title,status,cover_image_thumbnail',
ids: topic_ids.join(',')
}
}, function (err, res, result) {
if (err || !result || !Array.isArray(result.entries)) handleApiError(err, res, result, callback);
else callback(null, result.entries);
});
};
model.getUsersById = function (user_ids, callback) {
request({
baseUrl: config.api.baseUrl,
json: true,
timeout: 5000,
url: '/v1/users',
headers: {
'User-Agent': config.api.user_agent
},
qs: {
fields: 'id,username,role,picture_url,profile_url',
ids: user_ids.join(',')
}
}, function (err, res, result) {
if (err || !result || !Array.isArray(result.entries)) handleApiError(err, res, result, callback);
else callback(null, result.entries);
});
};
model._formatError = function (err, opts) {
if (opts) for (var prop in opts) if (opts.hasOwnProperty(prop)) err[prop] = opts[prop];
return err;
};
model._formatTimestamp = function (timestamp) {
if (!timestamp) return null;
timestamp = new Date(timestamp);
return {
epoch: timestamp.getTime(),
iso: timestamp.toISOString()
};
};
var handleApiError = function (err, res, result, callback) {
if (err) callback(err);
else if (res && res.statusCode && result && result.error) callback(model._formatError(new Error(), result));
else callback(new Error('Incorrect'));
};