@open-tender/store
Version:
A library of hooks, reducers, utility functions, and types for use with Open Tender applications that utilize our in-store POS API
79 lines (78 loc) • 3.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils_1 = require("@open-tender/utils");
var react_1 = require("react");
var parseSwipeCard = function (data) {
try {
var parts = data.split('?');
var code = parts[0].slice(1);
return code.length > 36 ? null : code;
}
catch (err) {
return null;
}
};
var useCardSwipe = function (api, parse) {
if (parse === void 0) { parse = true; }
var isAborted = (0, react_1.useRef)(false);
var _a = (0, react_1.useState)(null), code = _a[0], setCode = _a[1];
var _b = (0, react_1.useState)(null), error = _b[0], setError = _b[1];
(0, react_1.useEffect)(function () {
return function () {
isAborted.current = true;
};
}, []);
var read = (0, react_1.useCallback)(function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
var data, err_1, detail;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, api.getCardRead()];
case 1:
data = (_a.sent()).data;
if (parse)
data = parseSwipeCard(data);
data ? setCode(data) : setError('Could not read card. Please try again.');
if (!isAborted.current) {
data
? setCode(data)
: setError('Could not read card. Please try again.');
}
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
if (!isAborted.current) {
detail = (0, utils_1.handleRespError)(err_1).detail;
setError(detail || 'Unknown erorr');
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); }, [api, parse]);
var cancel = (0, react_1.useCallback)(function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
var err_2, detail;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, api.postCardCancel()];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_2 = _a.sent();
if (!isAborted.current) {
detail = (0, utils_1.handleRespError)(err_2).detail;
setError(detail || 'Unknown erorr');
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); }, [api]);
return (0, react_1.useMemo)(function () { return ({ code: code, error: error, read: read, cancel: cancel }); }, [code, error, read, cancel]);
};
exports.default = useCardSwipe;