UNPKG

@stackend/api

Version:

JS bindings to api.stackend.com

446 lines 19.1 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.mutation = exports.query = exports.escapeQueryTerm = exports.paginationArgs = exports.getCheckout = exports.cartBuyerIdentityUpdate = exports.cartLinesRemove = exports.cartLinesAdd = exports.cartLinesUpdate = exports.createCart = exports.getCart = exports.getCollections = exports.getCollection = exports.listProductsAndTypes = exports.listProducts = exports.getProduct = exports.listProductTypes = exports.API_VERSION = void 0; var api_1 = require("../api"); var index_1 = require("./index"); var collectionQuery_1 = __importDefault(require("./querries/collectionQuery")); var fullProductQuery_1 = __importDefault(require("./querries/fullProductQuery")); var checkoutQuery_1 = __importDefault(require("./querries/checkoutQuery")); var productListingQuery_1 = __importDefault(require("./querries/productListingQuery")); var productTypesQuery_1 = __importDefault(require("./querries/productTypesQuery")); var graphql_1 = require("../util/graphql"); var cartQuery_1 = __importDefault(require("./querries/cartQuery")); exports.API_VERSION = '2023-04'; function getImageMaxWidth(shopState, value) { if (!value) { return shopState.defaults.imageMaxWidth; } return value > shopState.defaults.imageMaxWidth ? shopState.defaults.imageMaxWidth : value; } function getImageListingMaxWidth(shopState, value) { if (!value) { return shopState.defaults.listingImageMaxWidth; } return value > shopState.defaults.listingImageMaxWidth ? shopState.defaults.listingImageMaxWidth : value; } /** * List product types * @param req * @returns {Thunk<ListProductTypesResult>} */ function listProductTypes(req) { return query({ query: "".concat((0, productTypesQuery_1.default)(req.first || 250)) /* 250 is max allowed */ }); } exports.listProductTypes = listProductTypes; /** * Get a product */ function getProduct(req) { return function (dispatch, getState) { var shopState = getState().shop; var imw = getImageMaxWidth(shopState, req.imageMaxWidth); return dispatch(query({ query: "product (handle: ".concat(escapeQueryTerm(req.handle), ") {\n ").concat((0, fullProductQuery_1.default)(imw, true), "\n }") })); }; } exports.getProduct = getProduct; /** * List products * @param req */ function listProducts(req) { return function (dispatch, getState) { var shopState = getState().shop; req.imageMaxWidth = getImageListingMaxWidth(shopState, req.imageMaxWidth); return dispatch(query({ query: (0, productListingQuery_1.default)(req) })); }; } exports.listProducts = listProducts; /** * List products and types * @param req */ function listProductsAndTypes(req) { return function (dispatch, getState) { var shopState = getState().shop; req.imageMaxWidth = getImageListingMaxWidth(shopState, req.imageMaxWidth); return dispatch(query({ query: "".concat((0, productListingQuery_1.default)(req), ", ").concat((0, productTypesQuery_1.default)(250)) /* 250 is max allowed */ })); }; } exports.listProductsAndTypes = listProductsAndTypes; /** * Get a collection * @param req */ function getCollection(req) { return function (dispatch, getState) { var shopState = getState().shop; var imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return dispatch(query({ query: "collection (handle: ".concat(escapeQueryTerm(req.handle), ") {\n ").concat((0, collectionQuery_1.default)(imw), "\n }") })); }; } exports.getCollection = getCollection; /** * List collections * @param req */ function getCollections(req) { return query({ query: "collections (first: 100, sortKey: TITLE) {\n edges {\n node {\n id,\n handle,\n title,\n description\n }\n }\n }" }); } exports.getCollections = getCollections; /** * Get a cart * @param req */ function getCart(req) { return function (dispatch, getState) { var shopState = getState().shop; var imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return dispatch(query({ query: "cart (id: ".concat((0, graphql_1.toQueryParameters)(req.cartId), ") {\n ").concat((0, cartQuery_1.default)(true, imw), "\n }") })); }; } exports.getCart = getCart; /** * Create a cart. * @param req */ function createCart(req) { var _this = this; return function (dispatch, getState) { return __awaiter(_this, void 0, void 0, function () { var shopState, imw, r; return __generator(this, function (_a) { switch (_a.label) { case 0: shopState = getState().shop; imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return [4 /*yield*/, dispatch(mutation({ mutation: "mutation {\n cartCreate ( input: {\n lines: ".concat((0, graphql_1.toQueryParameters)(req.lines || []), "\n ").concat(req.buyerIdentity ? ', buyerIdentity: ' + buyerIdentityToQueryParameters(req.buyerIdentity) : '', "\n }) {\n cart { ").concat((0, cartQuery_1.default)(req.lines.length !== 0, imw), " },\n userErrors { code, field, message }\n }\n }") }))]; case 1: r = _a.sent(); return [2 /*return*/, newModifyCartResult(r, 'cartCreate')]; } }); }); }; } exports.createCart = createCart; /** * Convert to ModifyCartResult * @param r * @param pfx */ function newModifyCartResult(r, pfx) { r.cart = null; if (r[pfx]) { if (r[pfx].cart) { r.cart = r[pfx].cart; } if (r[pfx].userErrors) { r.userErrors = r[pfx].userErrors; } delete r[pfx]; } return r; } function cartLinesUpdate(req) { var _this = this; return function (dispatch, getState) { return __awaiter(_this, void 0, void 0, function () { var shopState, imw, r; return __generator(this, function (_a) { switch (_a.label) { case 0: shopState = getState().shop; imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return [4 /*yield*/, dispatch(mutation({ mutation: "mutation {\n cartLinesUpdate(cartId: ".concat(JSON.stringify(req.cartId), ", lines: ").concat((0, graphql_1.toQueryParameters)(req.lines), ") {\n cart { ").concat((0, cartQuery_1.default)(true, imw), " },\n userErrors { code, field, message }\n }\n }") }))]; case 1: r = _a.sent(); return [2 /*return*/, newModifyCartResult(r, 'cartLinesUpdate')]; } }); }); }; } exports.cartLinesUpdate = cartLinesUpdate; function cartLinesAdd(req) { var _this = this; return function (dispatch, getState) { return __awaiter(_this, void 0, void 0, function () { var shopState, imw, r; return __generator(this, function (_a) { switch (_a.label) { case 0: shopState = getState().shop; imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return [4 /*yield*/, dispatch(mutation({ mutation: "mutation {\n cartLinesAdd(cartId: ".concat(JSON.stringify(req.cartId), ", lines: ").concat((0, graphql_1.toQueryParameters)(req.lines), "\n ) {\n cart { ").concat((0, cartQuery_1.default)(true, imw), " },\n userErrors { code, field, message }\n }\n }") }))]; case 1: r = _a.sent(); return [2 /*return*/, newModifyCartResult(r, 'cartLinesAdd')]; } }); }); }; } exports.cartLinesAdd = cartLinesAdd; function cartLinesRemove(req) { var _this = this; return function (dispatch, getState) { return __awaiter(_this, void 0, void 0, function () { var shopState, imw, r; return __generator(this, function (_a) { switch (_a.label) { case 0: shopState = getState().shop; imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return [4 /*yield*/, dispatch(mutation({ mutation: "mutation {\n cartLinesRemove(cartId: ".concat(JSON.stringify(req.cartId), ", lineIds: ").concat(JSON.stringify(req.lineIds), ") {\n cart { ").concat((0, cartQuery_1.default)(false, imw), " },\n userErrors { code, field, message }\n }\n }") }))]; case 1: r = _a.sent(); return [2 /*return*/, newModifyCartResult(r, 'cartLinesRemove')]; } }); }); }; } exports.cartLinesRemove = cartLinesRemove; function cartBuyerIdentityUpdate(req) { var _this = this; return function (dispatch, getState) { return __awaiter(_this, void 0, void 0, function () { var shopState, imw, r; return __generator(this, function (_a) { switch (_a.label) { case 0: shopState = getState().shop; imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); return [4 /*yield*/, dispatch(mutation({ mutation: "mutation {\n cartBuyerIdentityUpdate(\n cartId: ".concat(JSON.stringify(req.cartId), "\n ").concat(req.buyerIdentity && ', buyerIdentity: ' + buyerIdentityToQueryParameters(req.buyerIdentity), "\n ) {\n cart { ").concat((0, cartQuery_1.default)(false, imw), " },\n userErrors { code, field, message }\n }\n }") }))]; case 1: r = _a.sent(); return [2 /*return*/, newModifyCartResult(r, 'cartBuyerIdentityUpdate')]; } }); }); }; } exports.cartBuyerIdentityUpdate = cartBuyerIdentityUpdate; function buyerIdentityToQueryParameters(buyerIdentity) { var r = '{'; var i = 0; for (var _i = 0, _a = Object.keys(buyerIdentity); _i < _a.length; _i++) { var k = _a[_i]; if (i !== 0) { r += ','; } var v = buyerIdentity[k]; if (k === 'countryCode') { r += k + ':' + v; } else { r += k + ':' + JSON.stringify(v); } i++; } r += '}'; return r; } /** * Get a checkout * @param req */ function getCheckout(req) { return function (dispatch, getState) { var shopState = getState().shop; var imw = getImageListingMaxWidth(shopState, req.imageMaxWidth); // FIXME: handle getShippingRates and getProductData var getProductData = true; var x = req; return dispatch(query({ query: "node (id: ".concat(escapeQueryTerm(req.checkoutId), ") {\n ... on Checkout {\n ").concat((0, checkoutQuery_1.default)(x.getShippingRates || false, getProductData, imw), "\n }\n }"), aliases: { node: 'checkout' } })); }; } exports.getCheckout = getCheckout; /** * Construct pagination args * @param req * @param args * @returns {string|string} */ function paginationArgs(req, args) { var r = args || ''; var first = req.first; if (typeof req.first === 'undefined' && typeof req.last === 'undefined') { first = 10; } if (first) { r = appendArg(r, 'first', String(parseInt(first))); } if (req.after) { r = appendArg(r, 'after', escapeQueryTerm(req.after)); } if (req.last) { r = appendArg(r, 'last', String(parseInt(req.last))); } if (req.before) { r = appendArg(r, 'before', escapeQueryTerm(req.before)); } return r; } exports.paginationArgs = paginationArgs; function appendArg(args, name, value) { if (args.length !== 0) { args += ','; } args += name + ':' + value; return args; } /** * Escape and quote a query term * @param s * @returns {string} */ function escapeQueryTerm(s) { return JSON.stringify(s); } exports.escapeQueryTerm = escapeQueryTerm; /** * Perform a shopify query * @param query * @param headers * @param aliases change names of returned data * @returns {(function(*): Promise<XcapJsonResult>)|*} */ function query(_a) { var query = _a.query, headers = _a.headers, aliases = _a.aliases; return doPost({ query: query, isMutation: false, headers: headers, aliases: aliases }); } exports.query = query; /** * Perform a shopify mutation * @param mutation * @param headers * @param aliases change names of returned data * @returns {(function(*): Promise<XcapJsonResult>)|*} */ function mutation(_a) { var mutation = _a.mutation, headers = _a.headers, aliases = _a.aliases; return doPost({ query: mutation, isMutation: true, headers: headers, aliases: aliases }); } exports.mutation = mutation; /** * Perform a shopify query or mutation * @param query * @param headers * @param aliases change names of returned data * @param isMutation * @returns {(function(*): Promise<XcapJsonResult>)|*} */ function doPost(_a) { var _this = this; var query = _a.query, isMutation = _a.isMutation, headers = _a.headers, aliases = _a.aliases; return function (dispatch) { return __awaiter(_this, void 0, void 0, function () { var cfg, url, q, body, h, r, json; return __generator(this, function (_a) { switch (_a.label) { case 0: cfg = dispatch((0, index_1.getShopifyConfig)()); if (!cfg) { console.warn('Stackend: Shop not configured'); return [2 /*return*/, (0, api_1.newXcapJsonErrorResult)('Shop not configured')]; } url = 'https://' + cfg.domain + '/api/' + cfg.apiVersion + '/graphql.json'; q = isMutation ? query : '{' + query + '}'; body = JSON.stringify({ query: q, variables: null }); h = new Headers(); h.set('content-type', 'application/json'); h.set('x-shopify-storefront-access-token', cfg.accessToken); if (headers) { Object.keys(headers).forEach(function (k) { h.set(k, headers[k]); }); } return [4 /*yield*/, fetch(new Request(url, { body: body, headers: h, method: 'POST' }))]; case 1: r = _a.sent(); if (!r.ok) { console.error('Stackend: shopify query failed: ' + r.status + ' ' + r.statusText, q); return [2 /*return*/, (0, api_1.newXcapJsonErrorResult)(r.status + ' ' + r.statusText)]; } return [4 /*yield*/, r.json()]; case 2: json = _a.sent(); if (json.errors) { console.error('Stackend: shopify query failed: ', json.errors, q); return [2 /*return*/, (0, api_1.newXcapJsonErrorResult)(json.errors)]; } if (aliases) { Object.keys(aliases).forEach(function (key) { var newKey = aliases[key]; json.data[newKey] = json.data[key]; delete json.data[key]; }); } return [2 /*return*/, (0, api_1.newXcapJsonResult)('success', json.data)]; } }); }); }; } //# sourceMappingURL=shopify-clientside.js.map