-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
62 lines (59 loc) · 2.17 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
import { promisify } from 'util';
import { parseString } from 'xml2js';
import got from 'got';
import { xmlConductor, xmlVehicle, url, clean, valid, cleanCnh, validCnh } from './lib/util';
import DetranError from './lib/error';
import mapError from './lib/mapErrors';
class Service {
constructor(code, user, pass) {
this.code = code;
this.user = user;
this.pass = pass;
this._parseString = promisify(parseString);
this.headers = {
'Content-Type': 'text/xml',
};
}
async vehicle(plate) {
let isValid;
try {
const body = xmlVehicle(this.code, this.user, this.pass, plate);
const res = await got.post(url.vehicle, { headers: this.headers, body });
const resParse = await this._parseString(res.body, { explicitArray: false, trim: true });
const access = clean(resParse['soap:Envelope']['soap:Body']);
if (!access) return false;
isValid = valid(access.query);
if (isValid.status) return access.query;
throw new Error(access.query.DESCRICAO);
} catch (err) {
let _err = {};
if (await mapError.has(isValid.code)) {
_err = mapError.get(isValid.code);
}
const data = await { ...{ status: 500, message: err.message }, ..._err };
return new DetranError(data.message, data.status, data.name);
}
}
//
async conductor(cnh, cpf) {
let isValid;
try {
const body = xmlConductor(this.code, this.user, this.pass, cpf, cnh);
const res = await got.post(url.conductor, { headers: this.headers, body });
const resParse = await this._parseString(res.body, { explicitArray: false, trim: true });
const access = cleanCnh(resParse['soap:Envelope']['soap:Body']);
if (!access) return false;
isValid = validCnh(access.query);
if (isValid.status) return access.query;
throw new Error(access.query.DESCRICAO);
} catch (err) {
let _err = {};
if (mapError.has(isValid.code)) {
_err = mapError.get(isValid.code);
}
const data = { ...{ status: 500, message: err.message }, ..._err };
return new DetranError(data.message, data.status);
}
}
}
export default (code, user, pass) => new Service(code, user, pass);