This repository was archived by the owner on Mar 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
91 lines (75 loc) · 1.93 KB
/
index.js
File metadata and controls
91 lines (75 loc) · 1.93 KB
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
'use strict';
var https = require('https'),
apiUrl = '/api/v2/clean/',
apiTypes = ['address', 'birthdate', 'email', 'name', 'phone'];
// request sender
function reqSend (apiType, queries, callback) {
/* jshint validthis:true */
var req;
// handle invalid apiType
if (apiTypes.indexOf(apiType) === -1)
return callback({
code: -2,
message: 'node-dadata: invalid apiType'
});
// ok
else {
// set api endpoint
this.reqOptions.path = apiUrl + apiType;
// create request
req = https.request(this.reqOptions, function (res) {
var body = '';
// handle http error
if (res.statusCode !== 200)
return callback({
code: res.statusCode,
message: 'HTTP ERROR: bad status code'
});
// ok
else {
res.on('data', function (chunk) { body += chunk; });
res.on('end', function () { callback(null, JSON.parse(body)); });
}
});
// handle request error
req.on('error', function (err) {
callback({
code: -1,
message: 'REQUEST ERROR: ' + err.message
});
});
// send request body
// utf8 is by default
req.write(JSON.stringify(queries));
req.end();
}
}
// service constructor
function DaData (API_KEY, SECRET_KEY) {
// fail if no keys provided
if (!API_KEY || !SECRET_KEY) {
console.log('node-dadata: keys are strongly required');
return null;
}
// don't fail if someone have forgotten about new
else if (!(this instanceof DaData))
return new DaData(API_KEY, SECRET_KEY);
// ok
else {
// set request options
this.reqOptions = {
method: 'POST',
hostname: 'dadata.ru',
port: 443,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + API_KEY,
'X-Secret': SECRET_KEY
}
};
// return request sender
return reqSend.bind(this);
}
}
// exports
module.exports = DaData;