-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
112 lines (96 loc) · 2.61 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const soap = require('soap');
const get = require('lodash.get');
const config = require('./config');
const {
invoke,
prefix,
getError,
getResponse,
} = require('./helpers');
const WSDLValidator = require('./validate');
class PurolatorServices {
constructor(key, password) {
this.version = 2;
this.namespace = 'ns1';
this.authToken = new soap.BasicAuthSecurity(
key,
password,
);
}
static async sanitizeSoapRequest(name, method, body) {
const validationAdapter = new WSDLValidator(name);
await validationAdapter.build();
const schema = validationAdapter.get(method);
const errors = WSDLValidator.run(schema, body);
if (Object.keys(errors).length) {
const err = new Error('Validation failed');
err.errors = errors;
throw err;
}
}
async getAvailabilityOptions(body) {
return this.$req('ServiceAvailability.Options', body);
}
async validatePostalCode(body) {
return this.$req('ServiceAvailability.Validate', body);
}
async estimate(body, options = {}) {
const { full = false, ids = [] } = options;
const ShipmentEstimate = await this.$req(
`Estimating.${full ? 'Full' : 'Quick'}`,
body,
);
return !Array.isArray(ids) || !ids.length
? ShipmentEstimate
: ShipmentEstimate.filter(({ ServiceID }) =>
ids.includes(ServiceID),
);
}
$appendHeaders(e) {
const ns1 = `${config.datatypes}/v${this.version}`;
const headers = prefix(
{
RequestContext: {
Version: `${this.version}.0`,
Language: 'en',
GroupID: 'xxx',
RequestReference: this.constructor.name,
},
},
this.namespace,
);
e.wsdl.definitions.xmlns.ns1 = ns1;
e.wsdl.xmlnsInEnvelope = e.wsdl._xmlnsMap();
e.setSecurity(this.authToken);
e.addSoapHeader(headers);
return e;
}
async $req(serviceName, body) {
const payload = prefix(body, this.namespace);
const name = config.getWSDL(serviceName.split('.')[0]);
const { method, responseKey } = get(
config.responses,
serviceName,
);
const params = {
returnFault: true,
envelopeKey: 'SOAP-ENV',
xmlKey: this.namespace,
overrideRootElement: {
namespace: this.namespace,
},
};
await PurolatorServices.sanitizeSoapRequest(
name,
method,
body,
);
return soap
.createClientAsync(name, params)
.then(this.$appendHeaders.bind(this))
.then(invoke(`${method}Async`, payload))
.then(getResponse(responseKey))
.catch(getError);
}
}
module.exports = PurolatorServices;