UNPKG

@commercetools/discount-code-importer

Version:
272 lines (268 loc) 15.5 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _npmlog = _interopRequireDefault(require("npmlog")); var _lodash = _interopRequireDefault(require("lodash")); var _nodeFetch = _interopRequireDefault(require("node-fetch")); var _sdkClient = require("@commercetools/sdk-client"); var _apiRequestBuilder = require("@commercetools/api-request-builder"); var _sdkMiddlewareAuth = require("@commercetools/sdk-middleware-auth"); var _sdkMiddlewareHttp = require("@commercetools/sdk-middleware-http"); var _sdkMiddlewareUserAgent = require("@commercetools/sdk-middleware-user-agent"); var _syncActions = require("@commercetools/sync-actions"); var _package = _interopRequireDefault(require("../package.json")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } var DiscountCodeImportError = /*#__PURE__*/function (_Error) { function DiscountCodeImportError(message) { var _this; var summary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'No summary provided.'; var error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; _classCallCheck(this, DiscountCodeImportError); _this = _callSuper(this, DiscountCodeImportError, [message]); _this.message = message; _this.summary = summary; _this.error = error; return _this; } _inherits(DiscountCodeImportError, _Error); return _createClass(DiscountCodeImportError); }(/*#__PURE__*/_wrapNativeSuper(Error)); var DiscountCodeImport = exports["default"] = /*#__PURE__*/function () { // Set flowtype annotations function DiscountCodeImport(options, logger) { _classCallCheck(this, DiscountCodeImport); if (!options.apiConfig) throw new DiscountCodeImportError('The contructor must be passed an `apiConfig` object'); if (options.batchSize > 200) throw new DiscountCodeImportError('The `batchSize` must not be more than 200'); this.apiConfig = options.apiConfig; this.accessToken = options.accessToken; this.batchSize = options.batchSize || 50; this.continueOnProblems = options.continueOnProblems || false; this.client = (0, _sdkClient.createClient)({ middlewares: [(0, _sdkMiddlewareAuth.createAuthMiddlewareForClientCredentialsFlow)(_objectSpread(_objectSpread({}, this.apiConfig), {}, { fetch: _nodeFetch["default"] })), (0, _sdkMiddlewareUserAgent.createUserAgentMiddleware)({ libraryName: _package["default"].name, libraryVersion: _package["default"].version }), (0, _sdkMiddlewareHttp.createHttpMiddleware)({ host: this.apiConfig.apiUrl, fetch: _nodeFetch["default"] })] }); this.syncDiscountCodes = (0, _syncActions.createSyncDiscountCodes)(); this.logger = logger || { error: _npmlog["default"].error.bind(this, ''), warn: _npmlog["default"].warn.bind(this, ''), info: _npmlog["default"].info.bind(this, ''), verbose: _npmlog["default"].verbose.bind(this, '') }; this._resetSummary(); } // Use static method because this is not called on any instance return _createClass(DiscountCodeImport, [{ key: "processStream", value: // Wrapper function for compatibility with CLI function processStream(chunk, cb) { this.logger.verbose("Starting conversion of ".concat(chunk.length, " discount codes")); return this._processBatches(chunk).then(cb); // No catch block as errors will be caught in the CLI } // Public function for direct module usage }, { key: "run", value: function run(codes) { return this._processBatches(codes); } }, { key: "_processBatches", value: function _processBatches(codes) { var _this2 = this; // Batch to `batchSize` to reduce necessary fetch API calls var batchedList = _lodash["default"].chunk(codes, this.batchSize); var functionsList = batchedList.map(function (codeObjects) { return function () { // Build predicate and fetch existing code var predicate = DiscountCodeImport._buildPredicate(codeObjects); var service = _this2._createService(); var uri = service.where(predicate).perPage(_this2.batchSize).build(); var req = _this2._buildRequest(uri, 'GET'); return _this2.client.execute(req).then(function (_ref) { var existingCodes = _ref.body.results; return _this2._createOrUpdate(codeObjects, existingCodes); }); }; }); return DiscountCodeImport.promiseMapSerially(functionsList).then(function () { return Promise.resolve(); })["catch"]( // eslint-disable-next-line function (caughtError) { _this2.logger.error(caughtError.message || caughtError); return new DiscountCodeImportError('Processing batches failed', caughtError.message || caughtError, _this2._summary); }); } }, { key: "_createOrUpdate", value: function _createOrUpdate(newCodes, existingCodes) { var _this3 = this; return Promise.all(newCodes.map(function (newCode) { var existingCode = _lodash["default"].find(existingCodes, ['code', newCode.code]); if (existingCode) return _this3._update(newCode, existingCode).then(function (response) { if ((response === null || response === void 0 ? void 0 : response.statusCode) === 304) _this3._summary.unchanged += 1;else _this3._summary.updated += 1; return Promise.resolve(); })["catch"](function (error) { if (_this3.continueOnProblems) { _this3._summary.updateErrorCount += 1; _this3._summary.errors.push(error.message || error); // eslint-disable-next-line max-len var _msg = 'Update error occured but ignored. See summary for details'; _this3.logger.error(_msg); return Promise.resolve(); } // eslint-disable-next-line max-len var msg = 'Process stopped due to error while creating discount code. See summary for details'; _this3.logger.error(msg); _this3._summary.updateErrorCount += 1; _this3._summary.errors.push(error.message || error); return Promise.reject(error); }); return _this3._create(newCode).then(function () { _this3._summary.created += 1; return Promise.resolve(); })["catch"](function (error) { if (_this3.continueOnProblems) { _this3._summary.createErrorCount += 1; _this3._summary.errors.push(error.message || error); // eslint-disable-next-line max-len var _msg2 = 'Create error occured but ignored. See summary for details'; _this3.logger.error(_msg2); return Promise.resolve(); } // eslint-disable-next-line max-len var msg = 'Process stopped due to error while creating discount code. See summary for details'; _this3.logger.error(msg); _this3._summary.createErrorCount += 1; _this3._summary.errors.push(error.message || error); return Promise.reject(error); }); })); } }, { key: "_update", value: function _update(newCode, existingCode) { var actions = this.syncDiscountCodes.buildActions(newCode, existingCode); // don't call API if there's no update action if (!actions.length) return Promise.resolve({ statusCode: 304 }); var service = this._createService(); var uri = service.byId(existingCode.id).build(); var body = { version: existingCode.version, actions: actions }; var req = this._buildRequest(uri, 'POST', body); this.logger.verbose('Updating existing code entry'); return this.client.execute(req); } }, { key: "_create", value: function _create(code) { var service = this._createService(); var uri = service.build(); var req = this._buildRequest(uri, 'POST', code); this.logger.verbose('Creating new code entry'); return this.client.execute(req); } }, { key: "_createService", value: function _createService() { return (0, _apiRequestBuilder.createRequestBuilder)({ projectKey: this.apiConfig.projectKey }).discountCodes; } }, { key: "_resetSummary", value: function _resetSummary() { this._summary = { created: 0, updated: 0, unchanged: 0, createErrorCount: 0, updateErrorCount: 0, errors: [] }; return this._summary; } }, { key: "_buildRequest", value: function _buildRequest(uri, method, body) { var request = { uri: uri, method: method }; if (body) request.body = body; if (this.accessToken) request.headers = { Authorization: "Bearer ".concat(this.accessToken) }; return request; } }, { key: "summaryReport", value: function summaryReport() { var _this$_summary = this._summary, created = _this$_summary.created, updated = _this$_summary.updated, unchanged = _this$_summary.unchanged, createErrorCount = _this$_summary.createErrorCount, updateErrorCount = _this$_summary.updateErrorCount; var message = ''; if (created + updated + createErrorCount + updateErrorCount === 0) message = 'Summary: nothing to do, everything is fine'; // eslint-disable-next-line max-len else message = "Summary: there were ".concat(created + updated, " successfully imported discount codes (").concat(created, " were newly created, ").concat(updated, " were updated and ").concat(unchanged, " were unchanged)."); if (createErrorCount || updateErrorCount) // eslint-disable-next-line max-len message += " ".concat(createErrorCount + updateErrorCount, " errors occured (").concat(createErrorCount, " create errors and ").concat(updateErrorCount, " update errors.)"); return { reportMessage: message, detailedSummary: this._summary }; } }], [{ key: "_buildPredicate", value: function _buildPredicate(codeObjects) { var predicateArray = _lodash["default"].map(codeObjects, 'code'); return "code in (\"".concat(predicateArray.join('", "'), "\")"); } }, { key: "promiseMapSerially", value: function promiseMapSerially(functions) { return functions.reduce(function (promise, promiseReturningFunction) { return promise.then(function () { return promiseReturningFunction(); }); }, Promise.resolve()); } }]); }();