forked from i11v/temp-mail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·97 lines (82 loc) · 2.14 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
97
const crypto = require('crypto');
const https = require('https');
/**
* @type {string}
* @const
*/
const API_URL = 'https://api.temp-mail.ru';
/**
* Makes GET request
* @param {string} url
* @returns {Promise}
*/
function get(url) {
return new Promise((resolve, reject) => {
https
.get(url, (res) => {
if (res.statusCode < 200 || res.statusCode > 299) {
reject(new Error(`Request failed: ${res.statusCode}`));
}
let data = '';
res
.on('data', (chunk) => { data += chunk; })
.on('end', () => resolve(data));
})
.on('error', reject);
});
}
/**
* Generates MD5 hash from email
* @param {string} email
* @returns {string}
*/
function getEmailHash(email) {
return crypto.createHash('md5').update(email).digest('hex');
}
/**
* Generates random email in given domains
* @param {Array} domains
* @param {number} [len=7]
* @returns {string}
*/
function getRandomEmail(domains, len = 7) {
const name = Math.random().toString(36).substring(len);
const domain = domains[Math.floor(Math.random() * domains.length)];
return name + domain;
}
/**
* Receives available domains
* @returns {Promise.<Array, Error>}
*/
function getAvailableDomains() {
return get(`${API_URL}/request/domains/format/json/`).then(JSON.parse);
}
/**
* Generates email on temp-mail.ru
* @param {number} [len]
* @returns {Promise.<String, Error>}
*/
function generateEmail(len) {
return getAvailableDomains()
.then(availableDomains => getRandomEmail(availableDomains, len));
}
/**
* Receives inbox from temp-mail.ru
* @param {string} email
* @returns {Promise.<(Object|Array), Error>}
*/
function getInbox(email) {
if (!email) {
throw new Error('Please specify email');
}
return get(`${API_URL}/request/mail/id/${getEmailHash(email)}/format/json/`).then(JSON.parse);
}
function deleteMail(mailId) {
return new Promise((resolve, reject) => {
if (!mailId) {
return reject('Please specify mail identifier');
}
return get(`${API_URL}/request/delete/id/${mailId}/format/json/`).then(JSON.parse);
});
}
module.exports = { generateEmail, getInbox, deleteMail };