class CdekService {
constructor(login, secret, baseUrl = 'https://api.cdek.ru/v2') {
this.login = login;
this.secret = secret;
this.baseUrl = baseUrl;
this.authToken = null;
this.requestData = null;
}
process(requestData, body) {
this.requestData = { ...requestData, ...(JSON.parse(body) || {}) };
if (!this.requestData.action) {
this.sendValidationError('Action is required');
}
this.getAuthToken();
switch (this.requestData.action) {
case 'offices':
this.sendResponse(this.getOffices());
break;
case 'calculate':
this.sendResponse(this.calculate());
break;
default:
this.sendValidationError('Unknown action');
}
}
sendValidationError(message) {
console.error(message);
process.exit(1);
}
async getAuthToken() {
try {
const response = await axios.post(`${this.baseUrl}/oauth/token`, {
grant_type: 'client_credentials',
client_id: this.login,
client_secret: this.secret,
});
if (response.data.access_token) {
this.authToken = response.data.access_token;
} else {
throw new Error('Server not authorized to CDEK API');
}
} catch (error) {
console.error('Error acquiring token:', error.message);
this.sendError(error.message);
}
}
async httpRequest(method, data, useFormData = false, useJson = false) {
const headers = {
'Accept': 'application/json',
};
if (this.authToken) {
headers['Authorization'] = `Bearer ${this.authToken}`;
}
try {
const response = await axios({
method: 'post',
url: `${this.baseUrl}/${method}`,
headers,
data: useJson ? JSON.stringify(data) : data,
});
return response.data;
} catch (error) {
throw new Error(error.message);
}
}
sendResponse(data) {
console.log(data);
process.exit(0);
}
async getOffices() {
return this.httpRequest('deliverypoints', this.requestData);
}
async calculate() {
return this.httpRequest('calculator/tarifflist', this.requestData, false, true);
}
}
const cdekService = new CdekService('LOGIN', 'PASS');
// Assume req.query and requestBody contain the necessary data
router.get('/service', async (req, res) =>{
cdekService.process(req.query, req.body);
})