diff --git a/src/moysklad-client/client/methods/chain.js b/src/moysklad-client/client/methods/chain.js index 660a8ce..368c57a 100644 --- a/src/moysklad-client/client/methods/chain.js +++ b/src/moysklad-client/client/methods/chain.js @@ -4,8 +4,7 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var _ = require('lodash') - , callbackAdapter = require('../../../tools/index').callbackAdapter; +var _ = require('lodash'); var chain = function () { return _.chain(this.load.apply(this, arguments)); diff --git a/src/moysklad-client/client/methods/del.js b/src/moysklad-client/client/methods/del.js index d75c9a5..bc0e25d 100644 --- a/src/moysklad-client/client/methods/del.js +++ b/src/moysklad-client/client/methods/del.js @@ -4,10 +4,10 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var _ = require('lodash') - , callbackAdapter = require('../../../tools/index').callbackAdapter; +var _ = require('lodash'), + callbackAdapter = require('project/callbackAdapter'); -//TODO Ограничение на кол-во сохраняемых объектов в коллекции (проверить) +//TODO Ограничение на кол-во удаляемых объектов в коллекции (проверить) /** * Del. Удаляет сущность или список сущностей. @@ -19,8 +19,9 @@ 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; @@ -28,7 +29,7 @@ var del = function () { 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); diff --git a/src/moysklad-client/client/methods/first.js b/src/moysklad-client/client/methods/first.js index 9e57900..f688a75 100644 --- a/src/moysklad-client/client/methods/first.js +++ b/src/moysklad-client/client/methods/first.js @@ -4,8 +4,8 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var _ = require('lodash') - , callbackAdapter = require('../../../tools/index').callbackAdapter; +var _ = require('lodash'), + callbackAdapter = require('project/callbackAdapter'); /** * First. Возвращает первую сущность из списка сущностей согласно запросу. @@ -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; @@ -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); @@ -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; diff --git a/src/moysklad-client/client/methods/json-service.js b/src/moysklad-client/client/methods/json-service.js index 7800ed5..2bf42aa 100644 --- a/src/moysklad-client/client/methods/json-service.js +++ b/src/moysklad-client/client/methods/json-service.js @@ -4,21 +4,22 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -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); diff --git a/src/moysklad-client/client/methods/load.js b/src/moysklad-client/client/methods/load.js index 2824599..57d9bbb 100644 --- a/src/moysklad-client/client/methods/load.js +++ b/src/moysklad-client/client/methods/load.js @@ -4,8 +4,8 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var callbackAdapter = require('../../../tools/index').callbackAdapter - , _ = require('lodash'); +var _ = require('lodash'), + callbackAdapter = require('project/callbackAdapter'); //noinspection JSValidateJSDoc,JSCommentMatchesSignature /** @@ -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) { @@ -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; diff --git a/src/moysklad-client/client/methods/save.js b/src/moysklad-client/client/methods/save.js index af4763c..83e1d2b 100644 --- a/src/moysklad-client/client/methods/save.js +++ b/src/moysklad-client/client/methods/save.js @@ -4,8 +4,8 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var _ = require('lodash') - , callbackAdapter = require('../../../tools/index').callbackAdapter; +var _ = require('lodash'), + callbackAdapter = require('project/callbackAdapter'); //TODO Ограничение на кол-во сохраняемых объектов в коллекции (проверить) @@ -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); diff --git a/src/moysklad-client/client/methods/total.js b/src/moysklad-client/client/methods/total.js index 0e37e4b..d4faa1a 100644 --- a/src/moysklad-client/client/methods/total.js +++ b/src/moysklad-client/client/methods/total.js @@ -4,8 +4,8 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var _ = require('lodash') - , callbackAdapter = require('../../../tools/index').callbackAdapter; +var _ = require('lodash'), + callbackAdapter = require('project/callbackAdapter'); /** * @@ -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; @@ -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; diff --git a/src/moysklad-client/rest-clients/json/methods/fetch.js b/src/moysklad-client/rest-clients/json/methods/fetch.js index 2b16504..b5817a8 100644 --- a/src/moysklad-client/rest-clients/json/methods/fetch.js +++ b/src/moysklad-client/rest-clients/json/methods/fetch.js @@ -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) { diff --git a/src/moysklad-client/rest-clients/json/providerResponseHandler.js b/src/moysklad-client/rest-clients/json/providerResponseHandler.js index c03e831..7cd1752 100644 --- a/src/moysklad-client/rest-clients/json/providerResponseHandler.js +++ b/src/moysklad-client/rest-clients/json/providerResponseHandler.js @@ -1,11 +1,4 @@ -/** - * providerResponseHandler - * Date: 23.03.14 - * Vitaliy V. Makeev (w.makeev@gmail.com) - */ - -var _ = require('lodash') - , callbackAdapter = require('../../../tools').callbackAdapter; +var _ = require('lodash'); //TODO Часть кода providerResponseHandler'ов не оправданно дублируется .. > var providerResponseHandler = function (err, result, callback) { @@ -13,7 +6,6 @@ var providerResponseHandler = function (err, result, callback) { // .. этот кусок общий для всех if (!err) { - switch (result.response.responseCode) { //TODO Прописать все ошибки stock сервисов @@ -21,13 +13,13 @@ var providerResponseHandler = function (err, result, callback) { // ошибка пришла ввиде 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: @@ -36,9 +28,9 @@ 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) { @@ -46,7 +38,7 @@ var providerResponseHandler = function (err, result, callback) { } } - return callbackAdapter(err, result, callback); + return callback(err, result); }; module.exports = providerResponseHandler; \ No newline at end of file diff --git a/src/moysklad-client/rest-clients/ms-xml/providerResponseHandler.js b/src/moysklad-client/rest-clients/ms-xml/providerResponseHandler.js index 0b6cc19..d9b0a80 100644 --- a/src/moysklad-client/rest-clients/ms-xml/providerResponseHandler.js +++ b/src/moysklad-client/rest-clients/ms-xml/providerResponseHandler.js @@ -1,18 +1,9 @@ -/** - * providerResponseHandler - * Date: 23.03.14 - * Vitaliy V. Makeev (w.makeev@gmail.com) - */ - -var _ = require('lodash') - , callbackAdapter = require('../../../tools').callbackAdapter; - +var _ = require('lodash'); var providerResponseHandler = function (err, result, callback) { - var data; - -var _log = require('project/logger'), - _unmarshaller = require('project/unmarshaller').create(); + var data, + _log = require('project/logger'), + _unmarshaller = require('project/unmarshaller').create(); if (!err) { @@ -24,8 +15,8 @@ var _log = require('project/logger'), // ошибка авторизации case 401: - return callbackAdapter( - new Error('Request requires HTTP authentication'), result, callback); + return callback( + new Error('Request requires HTTP authentication'), result); // корректный ответ сервера (работаем с ним дальше) case 200: @@ -35,8 +26,8 @@ var _log = require('project/logger'), default: //TODO Надо парсить Html ответа и выделять описание ошибки _log.log('Server response: \n' + result.response.contentText); - return callbackAdapter( - new Error('Server response error ' + result.response.responseCode), result, callback); + return callback( + new Error('Server response error ' + result.response.responseCode), result); } if (result.response.contentText.length > 0) { @@ -51,7 +42,7 @@ var _log = require('project/logger'), result.type = data.name.localPart; - if (result.type == 'error') return callbackAdapter(new Error(data.value.message)); + if (result.type == 'error') return callback(new Error(data.value.message), result); if (result.type == 'collection') { result.obj = _.pluck(data.value.items, 'value'); @@ -67,7 +58,7 @@ var _log = require('project/logger'), } } - return callbackAdapter(err, result, callback); + return callback(err, result); }; module.exports = providerResponseHandler; \ No newline at end of file diff --git a/src/node_modules/project/callbackAdapter.js b/src/node_modules/project/callbackAdapter.js new file mode 100644 index 0000000..179cf37 --- /dev/null +++ b/src/node_modules/project/callbackAdapter.js @@ -0,0 +1,27 @@ + +// var Fiber + +// try { +// Fiber = require('fibers') +// } catch (e) {} + +var callbackAdapter = function (err, data, callback, flowControl) { + if (callback) { + return callback(err, data); + } else { + switch(true) { + // case Fiber && Fiber.current: + // case flowControl === 'sync': + + case flowControl === 'async' && Promise: + if (err) { return Promise.reject(err) } + else { return Promise.resolve(data) } + + default: + if (err) { throw err } + else { return data } + } + } +}; + +module.exports = callbackAdapter; diff --git a/src/node_modules/project/fetch/browser.js b/src/node_modules/project/fetch/browser.js index 1e1219b..74c464c 100644 --- a/src/node_modules/project/fetch/browser.js +++ b/src/node_modules/project/fetch/browser.js @@ -5,7 +5,6 @@ */ var _ = require('lodash'), - callbackAdapter = require('./../../../tools/callbackAdapter'), Queue = require('./queue'), log = require('project/logger'); diff --git a/src/node_modules/project/fetch/gs.js b/src/node_modules/project/fetch/gs.js index 6850eaa..3b1f749 100644 --- a/src/node_modules/project/fetch/gs.js +++ b/src/node_modules/project/fetch/gs.js @@ -4,10 +4,9 @@ * Vitaliy V. Makeev (w.makeev@gmail.com) */ -var _ = require('lodash') - , callbackAdapter = require('./../../../tools/callbackAdapter') - , Queue = require('./queue') - , log = require('project/logger'); +var _ = require('lodash'), + Queue = require('./queue'), + log = require('project/logger'); var queue = new Queue({ async: false @@ -56,7 +55,7 @@ var fetch = { request: _options }; - return callbackAdapter(err, result, callback); + callback(err, result); } }; diff --git a/src/node_modules/project/fetch/index.js b/src/node_modules/project/fetch/index.js index 8e19590..803c045 100644 --- a/src/node_modules/project/fetch/index.js +++ b/src/node_modules/project/fetch/index.js @@ -10,8 +10,7 @@ try { Fiber = require('fibers') } catch (e) {} -var nodeFetch = require('./node').fetch, - callbackAdapter = require('./../../../tools/callbackAdapter'); +var nodeFetch = require('./node').fetch; var fetch = { @@ -22,7 +21,7 @@ var fetch = { fiber.run({ error: err, data: data }); }); var result = Fiber.yield(); - return callbackAdapter(result.error, result.data, callback); + callback(result.error, result.data); } else { if (!callback) throw new Error('fetch: callback must be defined in async mode'); nodeFetch(options, callback); diff --git a/src/node_modules/project/fetch/node.js b/src/node_modules/project/fetch/node.js index 5c6329d..ac34711 100644 --- a/src/node_modules/project/fetch/node.js +++ b/src/node_modules/project/fetch/node.js @@ -6,8 +6,7 @@ var _ = require('lodash'), httpRequest = require('./node-https-request'), - Queue = require('./queue'), - callbackAdapter = require('./../../../tools/callbackAdapter'); + Queue = require('./queue'); var queue = new Queue(); diff --git a/src/tools/callbackAdapter.js b/src/tools/callbackAdapter.js deleted file mode 100644 index b51d17f..0000000 --- a/src/tools/callbackAdapter.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * callbackAdapter - * Date: 03.04.14 - * Vitaliy V. Makeev (w.makeev@gmail.com) - */ - -var callbackAdapter = function (err, data, callback) { - if (callback) { - return callback(err, data); - - } else { - if (err) - throw err; - else - return data; - } -}; - -module.exports = callbackAdapter; diff --git a/src/tools/index.js b/src/tools/index.js index 51645fa..01e2b04 100644 --- a/src/tools/index.js +++ b/src/tools/index.js @@ -127,8 +127,6 @@ exports.getBasicAuthHttpHeader = function (login, password) { }; -exports.callbackAdapter = require('./callbackAdapter'); - exports.Is = { 'args': function () { var args = arguments[0],