Skip to content

Commit

Permalink
Поддержка Promises #16
Browse files Browse the repository at this point in the history
Добавление поддержки Promises
  • Loading branch information
wmakeev committed Apr 22, 2016
1 parent 1361db1 commit 540bfc3
Show file tree
Hide file tree
Showing 17 changed files with 107 additions and 114 deletions.
3 changes: 1 addition & 2 deletions src/moysklad-client/client/methods/chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools/index').callbackAdapter;
var _ = require('lodash');

var chain = function () {
return _.chain(this.load.apply(this, arguments));
Expand Down
13 changes: 7 additions & 6 deletions src/moysklad-client/client/methods/del.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools/index').callbackAdapter;
var _ = require('lodash'),
callbackAdapter = require('project/callbackAdapter');

//TODO Ограничение на кол-во сохраняемых объектов в коллекции (проверить)
//TODO Ограничение на кол-во удаляемых объектов в коллекции (проверить)

/**
* Del. Удаляет сущность или список сущностей.
Expand All @@ -19,16 +19,17 @@ var _ = require('lodash')
*/
var del = function () {
//TODO Ensure
var args = _.toArray(arguments)
, callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null;
var that = this,
args = _.toArray(arguments),
callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null;

var restClient = this.getProvider('ms-xml'),
obj = null;

var putArgs = args.slice(0, args.length);

putArgs.push(function (err, data) {
obj = callbackAdapter(err, data.obj, callback);
obj = callbackAdapter(err, data.obj, callback, that.options.flowControl);
});

restClient.del.apply(restClient, putArgs);
Expand Down
14 changes: 7 additions & 7 deletions src/moysklad-client/client/methods/first.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools/index').callbackAdapter;
var _ = require('lodash'),
callbackAdapter = require('project/callbackAdapter');

/**
* First. Возвращает первую сущность из списка сущностей согласно запросу.
Expand All @@ -17,6 +17,7 @@ var _ = require('lodash')
*/
var first = function (type, query, callback) {
//TODO Ensure
var that = this;
var _restClient = this.getProvider('ms-xml'),
_obj = null,
_queryParametersList;
Expand All @@ -25,7 +26,6 @@ var first = function (type, query, callback) {
var _params = _queryParametersList[paramsIndex];

if (_params && ('count' in _params ? _params.count !== 0 : true)) {

_restClient.get(type, _.extend({}, _params, { count: 1 }), function (err, data) {
if (err) return callback(err);

Expand All @@ -36,25 +36,25 @@ var first = function (type, query, callback) {
_firstFromParts(++paramsIndex, callback)
}
});

} else {
return callback(null, null);
}
}

// query
if (typeof query == 'object' && 'getQueryParameters' in query) {
if (typeof query === 'object' && 'getQueryParameters' in query) {
_queryParametersList = query.getQueryParameters(this.options.filterLimit);
}

//TODO Ничего не мешеает использовать first без query
// .. ошибка
else {
return callbackAdapter(new TypeError('Incorrect query parameter'), null, callback);
return callbackAdapter(new TypeError('Incorrect query parameter'),
null, callback, that.options.flowControl);
}

_firstFromParts(0, function (err, data) {
_obj = callbackAdapter(err, data, callback);
_obj = callbackAdapter(err, data, callback, that.options.flowControl);
});

return _obj;
Expand Down
15 changes: 8 additions & 7 deletions src/moysklad-client/client/methods/json-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,22 @@
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools/index').callbackAdapter;
var _ = require('lodash'),
callbackAdapter = require('project/callbackAdapter');

//TODO Вероятно нужно перенести этот модуль в rest-clients/json (для целостности пониманя работы модуля)

var callService = function (serviceName) {
var args = _.toArray(arguments)
, callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null
, _restClient = this.getProvider('json-services')
, _obj = null;
var that = this,
args = _.toArray(arguments),
callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null,
_restClient = this.getProvider('json-services'),
_obj = null;

var serviceArgs = args.slice(1, args.length - (callback ? 1 : 0));

serviceArgs.push(function (err, data) {
_obj = callbackAdapter(err, data.obj, callback);
_obj = callbackAdapter(err, data.obj, callback, that.options.flowControl);
});

_restClient[serviceName].apply(_restClient, serviceArgs);
Expand Down
26 changes: 14 additions & 12 deletions src/moysklad-client/client/methods/load.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* Vitaliy V. Makeev ([email protected])
*/

var callbackAdapter = require('../../../tools/index').callbackAdapter
, _ = require('lodash');
var _ = require('lodash'),
callbackAdapter = require('project/callbackAdapter');

//noinspection JSValidateJSDoc,JSCommentMatchesSignature
/**
Expand All @@ -19,12 +19,13 @@ var callbackAdapter = require('../../../tools/index').callbackAdapter
*/
var load = function (type, query) {
//TODO Ensure
var args = _.toArray(arguments)
, callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null
, options = typeof args[2] === 'object' ? args[2] : {}
, _queryParametersList
, _restClient = this.getProvider('ms-xml')
, _obj = null;
var that = this,
args = _.toArray(arguments),
callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null,
options = typeof args[2] === 'object' ? args[2] : {},
_queryParametersList,
_restClient = this.getProvider('ms-xml'),
_obj = null;

function loadPartial(paramsIndex, paging, cumulativeTotal, resultCollection, callback) {

Expand Down Expand Up @@ -69,27 +70,28 @@ var load = function (type, query) {
if (options.fileContent) params.fileContent = true;

_restClient.get(type, params, function (err, data) {
_obj = callbackAdapter(err, data.obj, callback);
_obj = callbackAdapter(err, data.obj, callback, that.options.flowControl);
});
}

// .. или query
else if (typeof query == 'object' && 'getQueryParameters' in query) {
//TODO Не забыть про options при написании документации
_queryParametersList = query.getQueryParameters(this.options.filterLimit);
_queryParametersList = query.getQueryParameters(that.options.filterLimit);

var paging = {};
if (_queryParametersList[0].start) paging.start = _queryParametersList[0].start;
if (_queryParametersList[0].count) paging.count = _queryParametersList[0].count;

loadPartial(0, paging, 0, [], function (err, data) {
_obj = callbackAdapter(err, data, callback);
_obj = callbackAdapter(err, data, callback, that.options.flowControl);
});
}

// .. ошибка
else {
return callbackAdapter(new TypeError('Incorrect uuid or query parameter'), null, callback);
return callbackAdapter(new TypeError('Incorrect uuid or query parameter'),
null, callback, that.options.flowControl);
}

return _obj;
Expand Down
13 changes: 7 additions & 6 deletions src/moysklad-client/client/methods/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools/index').callbackAdapter;
var _ = require('lodash'),
callbackAdapter = require('project/callbackAdapter');

//TODO Ограничение на кол-во сохраняемых объектов в коллекции (проверить)

Expand All @@ -19,16 +19,17 @@ var _ = require('lodash')
*/
var save = function () {
//TODO Ensure
var args = _.toArray(arguments)
, callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null;
var that = this,
args = _.toArray(arguments),
callback = typeof args.slice(-1)[0] === 'function' ? args.slice(-1)[0] : null;

var restClient = this.getProvider('ms-xml'),
var restClient = that.getProvider('ms-xml'),
obj = null;

var putArgs = args.slice(0, args.length);

putArgs.push(function (err, data) {
obj = callbackAdapter(err, data.obj, callback);
obj = callbackAdapter(err, data.obj, callback, that.options.flowControl);
});

restClient.put.apply(restClient, putArgs);
Expand Down
12 changes: 7 additions & 5 deletions src/moysklad-client/client/methods/total.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools/index').callbackAdapter;
var _ = require('lodash'),
callbackAdapter = require('project/callbackAdapter');

/**
*
Expand All @@ -16,7 +16,8 @@ var _ = require('lodash')
*/
var total = function (type, query, callback) {
//TODO Ensure
var _restClient = this.getProvider('ms-xml'),
var that = this,
_restClient = this.getProvider('ms-xml'),
_total = null,
_queryParametersList;

Expand All @@ -43,13 +44,14 @@ var total = function (type, query, callback) {
_queryParametersList = query.getQueryParameters();

_totalFromParts(0, 0, function (err, data) {
_total = callbackAdapter(err, data, callback);
_total = callbackAdapter(err, data, callback, that.options.flowControl);
});
}

// .. error
else {
return callbackAdapter(new TypeError('Incorrect query parameter'), null, callback);
return callbackAdapter(new TypeError('Incorrect query parameter'),
null, callback, that.options.flowControl);
}

return _total;
Expand Down
4 changes: 3 additions & 1 deletion src/moysklad-client/rest-clients/json/methods/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
var _ = require('lodash'),
moment = require('moment'),
clientProperties = require('./../../client-properties'),
callbackAdapter = require('project/callbackAdapter'),
fetchProviderRespHandler = require('./../providerResponseHandler'),
endPoint = clientProperties.baseUrl + '/rest';

module.exports = function fetch (options, callback) {
var _fetchProvider = require('project/fetch'),
var that = this,
_fetchProvider = require('project/fetch'),
queryString;

if (options.params) {
Expand Down
26 changes: 9 additions & 17 deletions src/moysklad-client/rest-clients/json/providerResponseHandler.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
/**
* providerResponseHandler
* Date: 23.03.14
* Vitaliy V. Makeev ([email protected])
*/

var _ = require('lodash')
, callbackAdapter = require('../../../tools').callbackAdapter;
var _ = require('lodash');

//TODO Часть кода providerResponseHandler'ов не оправданно дублируется .. >
var providerResponseHandler = function (err, result, callback) {
var _log = require('project/logger');

// .. этот кусок общий для всех
if (!err) {

switch (result.response.responseCode) {

//TODO Прописать все ошибки stock сервисов
//TODO Есть ли общие для всех ошибки (нужно ли выделять)?

// ошибка пришла ввиде XML сериализуем и обработаем ниже
case 500:
return callbackAdapter(
new Error('Server error 500'), result, callback);
return callback(
new Error('Server error 500'), result);

// ошибка авторизации
case 401:
return callbackAdapter(
new Error('Request requires HTTP authentication'), result, callback);
return callback(
new Error('Request requires HTTP authentication'), result);

// корректный ответ сервера (работаем с ним дальше)
case 200:
Expand All @@ -36,17 +28,17 @@ var providerResponseHandler = function (err, result, callback) {
// любой другой код ответа - ошибка
default:
//TODO ??? Надо парсить Html ответа и выделять описание ошибки
_log.log('Ответ сервера: \n' + result.response.contentText);
return callbackAdapter(
new Error('Server response error ' + result.response.responseCode), result, callback);
_log.log('Server response: \n' + result.response.contentText);
return callback(
new Error('Server response error ' + result.response.responseCode), result);
}

if (result.response.contentText.length > 0) {
result.obj = JSON.parse(result.response.contentText);
}
}

return callbackAdapter(err, result, callback);
return callback(err, result);
};

module.exports = providerResponseHandler;
Loading

0 comments on commit 540bfc3

Please sign in to comment.