@stackend/api
Version:
JS bindings to api.stackend.com
851 lines • 26.8 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cartToLineItems = exports.cartFindLine = exports.getParentProductType = exports.getProductTypeRoots = exports.toMoneyV2 = exports.getCountry = exports.getCountries = exports.getAddressFields = exports.setShippingAddress = exports.setCheckoutEmail = exports.selectShipping = exports.checkoutReplaceItems = exports.getCheckout = exports.createCheckout = exports.cartBuyerIdentityUpdate = exports.cartLinesRemove = exports.getCart = exports.cartLinesAdd = exports.cartLinesUpdate = exports.createCart = exports.getCollections = exports.getCollection = exports.getAllUniqueImages = exports.getProductSelection = exports.matchSelection = exports.findAllProductVariants = exports.findExactProductVariant = exports.findProductVariantByImage = exports.getLowestVariantPrice = exports.getVariantImage = exports.mapProductVariants = exports.forEachProductVariant = exports.getProductVariant = exports.getFirstImage = exports.listProductsAndTypes = exports.getProducts = exports.newGetProductsRequest = exports.getProduct = exports.newGetProductRequest = exports.listProducts = exports.newListProductsRequest = exports.applyDefaults = exports.parseProductSortKey = exports.ProductSortKeys = exports.listProductTypes = exports.storeShopConfiguration = exports.getShopConfiguration = exports.getShopifyConfig = exports.isShopEnabled = exports.AddressFieldName = void 0;
exports.cartNotifyProductAdded = void 0;
var api_1 = require("../api");
var util_1 = require("../util");
var graphql_1 = require("../util/graphql");
var ShopifyClientside = __importStar(require("./shopify-clientside"));
var AddressFieldName;
(function (AddressFieldName) {
AddressFieldName["FirstName"] = "firstName";
AddressFieldName["LastName"] = "lastName";
AddressFieldName["Country"] = "country";
AddressFieldName["City"] = "city";
AddressFieldName["PostalCode"] = "zip";
AddressFieldName["Zone"] = "province";
AddressFieldName["Address1"] = "address1";
AddressFieldName["Address2"] = "address2";
AddressFieldName["Phone"] = "phone";
AddressFieldName["Company"] = "company";
})(AddressFieldName = exports.AddressFieldName || (exports.AddressFieldName = {}));
/**
* Check if the shop is enabled
* @param community
*/
function isShopEnabled(community) {
if (!community) {
return false;
}
return typeof community.settings.shop != 'undefined';
}
exports.isShopEnabled = isShopEnabled;
/**
* Get shopify configuration from store
* @return null if disabled
*/
function getShopifyConfig() {
return function (dispatch, getState) {
var communities = getState().communities;
var community = communities.community;
if (!community || !community.settings.shop) {
return null;
}
return {
domain: community.settings.shop.domain,
accessToken: community.settings.shop.at,
countryCode: community.settings.shop.countryCode,
apiVersion: ShopifyClientside.API_VERSION
};
};
}
exports.getShopifyConfig = getShopifyConfig;
/**
* Get the shop configuration. Requires admin privs
* @returns {Thunk<XcapJsonResult>}
*/
function getShopConfiguration() {
return (0, api_1.getJson)({
url: '/shop/admin/get-config'
});
}
exports.getShopConfiguration = getShopConfiguration;
/**
* Store the shop configuration. Requires admin privs
* @param shop
* @param storeFrontAccessToken
* @param webhookKey
* @param enableCartNotifications
* @returns {Thunk<XcapJsonResult>}
*/
function storeShopConfiguration(_a) {
var shop = _a.shop, storeFrontAccessToken = _a.storeFrontAccessToken, webhookKey = _a.webhookKey, _b = _a.enableCartNotifications, enableCartNotifications = _b === void 0 ? false : _b;
return (0, api_1.post)({
url: '/shop/admin/store-config',
parameters: arguments
});
}
exports.storeShopConfiguration = storeShopConfiguration;
/**
* List product types
* @param req
* @returns {Thunk<ListProductTypesResult>}
*/
function listProductTypes(req) {
if ((0, api_1.isRunningServerSide)()) {
return (0, api_1.getJson)({
url: '/shop/list-product-types',
parameters: arguments
});
}
else {
return ShopifyClientside.listProductTypes(req);
}
}
exports.listProductTypes = listProductTypes;
var ProductSortKeys;
(function (ProductSortKeys) {
ProductSortKeys["VENDOR"] = "VENDOR";
ProductSortKeys["CREATED_AT"] = "CREATED_AT";
ProductSortKeys["ID"] = "ID";
ProductSortKeys["PRICE"] = "PRICE";
ProductSortKeys["PRODUCT_TYPE"] = "PRODUCT_TYPE";
ProductSortKeys["RELEVANCE"] = "RELEVANCE";
ProductSortKeys["TITLE"] = "TITLE";
ProductSortKeys["UPDATED_AT"] = "UPDATED_AT";
ProductSortKeys["BEST_SELLING"] = "BEST_SELLING";
})(ProductSortKeys = exports.ProductSortKeys || (exports.ProductSortKeys = {}));
/**
* Parse a product sort key
* @param sort
* @param defaultValue
*/
function parseProductSortKey(sort, defaultValue) {
if (!sort) {
return defaultValue || ProductSortKeys.RELEVANCE;
}
var v = ProductSortKeys[sort];
return v || defaultValue || ProductSortKeys.RELEVANCE;
}
exports.parseProductSortKey = parseProductSortKey;
function applyDefaults(req, defaults) {
if (!req.imageMaxWidth) {
req.imageMaxWidth = defaults.listingImageMaxWidth;
}
if (req.after) {
if (!req.first) {
req.first = defaults.pageSize;
}
}
else if (req.before) {
if (!req.last) {
req.last = defaults.pageSize;
}
}
else {
if (!req.first && !req.after) {
req.first = defaults.pageSize;
}
}
}
exports.applyDefaults = applyDefaults;
/**
* Create a new ListProductsRequest with default options
* @param req
*/
var newListProductsRequest = function (req) {
return function (dispatch, getState) {
if (!req) {
req = {};
}
applyDefaults(req, getState().shop.defaults);
return req;
};
};
exports.newListProductsRequest = newListProductsRequest;
/**
* List products
* @param req
* @returns {Thunk<ListProductsResult>}
*/
function listProducts(req) {
if ((0, api_1.isRunningServerSide)()) {
return (0, api_1.getJson)({
url: '/shop/list-products',
parameters: arguments
});
}
else {
return ShopifyClientside.listProducts(req);
}
}
exports.listProducts = listProducts;
/**
* Create a new GetProductRequest with default image sizes
* @param req GetProductRequest or handle
*/
var newGetProductRequest = function (req) {
return function (dispatch, getState) {
if (typeof req === 'string') {
req = {
handle: req
};
}
var defaults = getState().shop.defaults;
if (!req.imageMaxWidth) {
req.imageMaxWidth = defaults.imageMaxWidth;
}
return req;
};
};
exports.newGetProductRequest = newGetProductRequest;
/**
* Get a single product
* @param req
* @returns {Thunk<XcapJsonResult>}
*/
function getProduct(req) {
if ((0, api_1.isRunningServerSide)()) {
return (0, api_1.getJson)({
url: '/shop/get-product',
parameters: arguments
});
}
else {
return ShopifyClientside.getProduct(req);
}
}
exports.getProduct = getProduct;
/**
* Create a new GetProductsRequest with default image sizes
* @param req GetProductsRequest or handles
*/
var newGetProductsRequest = function (req) {
return function (dispatch, getState) {
if (Array.isArray(req)) {
req = {
handles: req
};
}
if (!req.imageMaxWidth) {
var defaults = getState().shop.defaults;
req.imageMaxWidth = defaults.imageMaxWidth;
}
return req;
};
};
exports.newGetProductsRequest = newGetProductsRequest;
/**
* Get multiple products
* @param req
* @returns {Thunk<XcapJsonResult>}
*/
function getProducts(req) {
return (0, api_1.getJson)({
url: '/shop/get-products',
parameters: arguments
});
// FIXME: Add client side version
}
exports.getProducts = getProducts;
/**
* List products and types
* @param req
* @returns {Thunk<XcapJsonResult>}
*/
function listProductsAndTypes(req) {
if ((0, api_1.isRunningServerSide)()) {
return (0, api_1.getJson)({
url: '/shop/list-products-and-types',
parameters: arguments
});
}
else {
return ShopifyClientside.listProductsAndTypes(req);
}
}
exports.listProductsAndTypes = listProductsAndTypes;
/**
* Get the first image of a product
* @param product
*/
function getFirstImage(product) {
if (!product) {
return null;
}
var images = product.images;
if (!images || images.edges.length === 0) {
return null;
}
return images.edges[0].node;
}
exports.getFirstImage = getFirstImage;
/**
* Get a product variant
* @param product
* @param variant
*/
function getProductVariant(product, variant) {
var n = product.variants.edges.find(function (v) {
return v.node.id === variant;
});
return n ? n.node : null;
}
exports.getProductVariant = getProductVariant;
/**
* Iterate product variants
* @param product
* @param predicate
*/
function forEachProductVariant(product, predicate) {
product.variants.edges.forEach(function (x, index) {
predicate(x.node, index, product);
});
}
exports.forEachProductVariant = forEachProductVariant;
/**
* Map each product variant
* @param product
* @param apply
*/
function mapProductVariants(product, apply) {
return product.variants.edges.map(function (x) { return apply(x.node, product); });
}
exports.mapProductVariants = mapProductVariants;
/**
* Get the variant image
*/
function getVariantImage(product, variant) {
var v = getProductVariant(product, variant);
return v ? v.image : null;
}
exports.getVariantImage = getVariantImage;
/**
* Get the lowest variant price available
* @param product
*/
function getLowestVariantPrice(product) {
var p = null;
forEachProductVariant(product, function (variant) {
if (p === null || variant.price.amount < p.amount) {
p = variant.price;
}
});
return p;
}
exports.getLowestVariantPrice = getLowestVariantPrice;
/**
* Find a product variant given an image
* @param product
* @param image
*/
function findProductVariantByImage(product, image) {
if (!product || !image) {
return null;
}
var x = product.variants.edges.find(function (v) {
var _a, _b;
return ((_b = (_a = v.node) === null || _a === void 0 ? void 0 : _a.image) === null || _b === void 0 ? void 0 : _b.url) === image.url;
});
return x ? x.node : null;
}
exports.findProductVariantByImage = findProductVariantByImage;
/**
* Given a selection, find the product variant
* @param product
* @param selection
*/
function findExactProductVariant(product, selection) {
if (!product || !selection || product.variants.edges.length === 0) {
return null;
}
var x = product.variants.edges.find(function (v) { return matchSelection(v.node, selection, false); });
return x ? x.node : null;
}
exports.findExactProductVariant = findExactProductVariant;
function findAllProductVariants(product, selection) {
if (!product || !selection || product.variants.edges.length === 0) {
return [];
}
var m = [];
product.variants.edges.forEach(function (v) {
if (matchSelection(v.node, selection, true)) {
m.push(v.node);
}
});
return m;
}
exports.findAllProductVariants = findAllProductVariants;
/**
* Check if a product variant matches the selection
* @param variant
* @param selection
* @param returnPartialMatches
*/
function matchSelection(variant, selection, returnPartialMatches) {
if (!variant) {
return false;
}
for (var _i = 0, _a = variant.selectedOptions; _i < _a.length; _i++) {
var o = _a[_i];
var x = selection[o.name];
if (x) {
if (x !== o.value) {
return false;
}
}
else {
if (!returnPartialMatches) {
return false;
}
}
}
return true;
}
exports.matchSelection = matchSelection;
/**
* Given a variant, construct the corresponding selection
* @param product
* @param variant
* @returns {Selection}
*/
function getProductSelection(product, variant) {
var s = {};
if (!product || !variant) {
return s;
}
for (var _i = 0, _a = variant.selectedOptions; _i < _a.length; _i++) {
var o = _a[_i];
s[o.name] = o.value;
}
return s;
}
exports.getProductSelection = getProductSelection;
/**
* Get unique product images, including variant images
* @param product
*/
function getAllUniqueImages(product) {
var images = [];
var s = new Set();
if (!product) {
return images;
}
(0, graphql_1.forEachGraphQLList)(product.images, function (img) {
if (!s.has(img.url)) {
images.push(img);
s.add(img.url);
}
});
(0, graphql_1.forEachGraphQLList)(product.variants, function (v) {
var img = v.image;
if (img && !s.has(img.url)) {
images.push(img);
s.add(img.url);
}
});
return images;
}
exports.getAllUniqueImages = getAllUniqueImages;
/**
* Get a collection of products
* @param req
* @returns {Thunk<XcapJsonResult>}
*/
function getCollection(req) {
if ((0, api_1.isRunningServerSide)()) {
return (0, api_1.getJson)({
url: '/shop/get-collection',
parameters: arguments
});
}
else {
return ShopifyClientside.getCollection(req);
}
}
exports.getCollection = getCollection;
/**
* Get all collections. Requires community admin privileges.
* @param req
* @returns {Thunk<XcapJsonResult>}
*/
function getCollections(req) {
if ((0, api_1.isRunningServerSide)()) {
return (0, api_1.getJson)({
url: '/shop/get-collections',
parameters: arguments
});
}
else {
return ShopifyClientside.getCollections(req);
}
}
exports.getCollections = getCollections;
/**
* Create a cart
* @param req
*/
function createCart(req) {
return ShopifyClientside.createCart(req);
}
exports.createCart = createCart;
/**
* Alter the contents of the cart. You can not add new lines using this request
* @param req
*/
function cartLinesUpdate(req) {
return ShopifyClientside.cartLinesUpdate(req);
}
exports.cartLinesUpdate = cartLinesUpdate;
/**
* Add products of the cart
* @param req
*/
function cartLinesAdd(req) {
return ShopifyClientside.cartLinesAdd(req);
}
exports.cartLinesAdd = cartLinesAdd;
/**
* Get a cart
* @param req
*/
function getCart(req) {
return ShopifyClientside.getCart(req);
}
exports.getCart = getCart;
/**
* Remove a product line from the cart
* @param req
*/
function cartLinesRemove(req) {
return ShopifyClientside.cartLinesRemove(req);
}
exports.cartLinesRemove = cartLinesRemove;
/**
* Update buyer identity or country
* @param req
*/
function cartBuyerIdentityUpdate(req) {
return ShopifyClientside.cartBuyerIdentityUpdate(req);
}
exports.cartBuyerIdentityUpdate = cartBuyerIdentityUpdate;
/**
* Create a checkout
* @param req
*/
function createCheckout(req) {
return (0, api_1.post)({
url: '/shop/checkout/create',
parameters: __assign(__assign({}, req), { input: JSON.stringify(req.input) })
});
}
exports.createCheckout = createCheckout;
/**
* Get a checkout given an id
* @param req
*/
function getCheckout(req) {
return (0, api_1.getJson)({
url: '/shop/checkout/get',
parameters: arguments
});
}
exports.getCheckout = getCheckout;
/**
* Replace the items in the checkout
* @param req
*/
function checkoutReplaceItems(req) {
return (0, api_1.post)({
url: '/shop/checkout/replace-items',
parameters: __assign(__assign({}, req), { lineItems: JSON.stringify(req.lineItems) })
});
}
exports.checkoutReplaceItems = checkoutReplaceItems;
/**
* Select shipping
* @param req
*/
function selectShipping(req) {
return (0, api_1.post)({
url: '/shop/checkout/set-shipping',
parameters: arguments
});
}
exports.selectShipping = selectShipping;
/**
* Set email
* @param req
*/
function setCheckoutEmail(req) {
return (0, api_1.post)({
url: '/shop/checkout/set-email',
parameters: arguments
});
}
exports.setCheckoutEmail = setCheckoutEmail;
/**
* Set shipping address
* @param req
*/
function setShippingAddress(req) {
var _a;
var p = (_a = {
checkoutId: req.checkoutId,
addressJson: JSON.stringify(req.address)
},
_a[api_1.COMMUNITY_PARAMETER] = req[api_1.COMMUNITY_PARAMETER],
_a);
return (0, api_1.post)({
url: '/shop/checkout/set-shipping-address',
parameters: p
});
}
exports.setShippingAddress = setShippingAddress;
/**
* Get the required address fields for the country using the specified locale.
* @param locale (Optional. falls back to community locale)
* @param countryCode
*/
function getAddressFields(_a) {
var _this = this;
var locale = _a.locale, countryCode = _a.countryCode;
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var l, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, dispatch((0, util_1.getLocale)(locale))];
case 1:
l = _a.sent();
return [4 /*yield*/, dispatch((0, api_1.getJson)({
url: '/shop/countries/get-address-fields',
parameters: { locale: l, countryCode: countryCode }
}))];
case 2:
r = _a.sent();
return [2 /*return*/, r.error ? [] : r.addressFields];
}
});
}); };
}
exports.getAddressFields = getAddressFields;
/**
* Get the list of countries
* @param locale
*/
function getCountries(_a) {
var _this = this;
var locale = _a.locale;
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var l, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, dispatch((0, util_1.getLocale)(locale))];
case 1:
l = _a.sent();
return [4 /*yield*/, dispatch((0, api_1.getJson)({
url: '/shop/countries/get-all',
parameters: { locale: l }
}))];
case 2:
r = _a.sent();
return [2 /*return*/, r.error ? [] : r.countries];
}
});
}); };
}
exports.getCountries = getCountries;
/**
* Get a country
* @param locale
* @param countryCode
*/
function getCountry(_a) {
var _this = this;
var locale = _a.locale, countryCode = _a.countryCode;
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var l, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, dispatch((0, util_1.getLocale)(locale))];
case 1:
l = _a.sent();
return [4 /*yield*/, dispatch((0, api_1.getJson)({
url: '/shop/countries/get',
parameters: { locale: l, countryCode: countryCode }
}))];
case 2:
r = _a.sent();
return [2 /*return*/, r.error ? null : r.country];
}
});
}); };
}
exports.getCountry = getCountry;
var CURRENCY_FORMATS = {};
/**
* Convert the amount to MoneyV2, adjusting to the currency correct number of decimals
* @param amount
* @param currencyCode
*/
function toMoneyV2(amount, currencyCode) {
var fmt = CURRENCY_FORMATS[currencyCode];
if (!fmt) {
fmt = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currencyCode,
useGrouping: false
});
CURRENCY_FORMATS[currencyCode] = fmt;
}
var a = fmt.format(amount);
// Remove currency code
a = a.replace(/[^0-9.\\-]/g, '');
return {
amount: a,
currencyCode: currencyCode
};
}
exports.toMoneyV2 = toMoneyV2;
/**
* Get the root nodes from a flat array of product types
* @param productTypes
*/
function getProductTypeRoots(productTypes) {
if (!productTypes) {
return [];
}
var x = new Set();
productTypes.forEach(function (p) {
if (p === '') {
return;
}
var v = p;
var i = v.indexOf('/');
if (i === -1) {
x.add(v);
}
else {
x.add(v.substring(0, i));
}
});
return Array.from(x);
}
exports.getProductTypeRoots = getProductTypeRoots;
/**
* Get the parent product type
* @param productType
*/
function getParentProductType(productType) {
if (!productType) {
return null;
}
var i = productType.lastIndexOf('/');
if (i === -1) {
return null;
}
return productType.substring(0, i);
}
exports.getParentProductType = getParentProductType;
function cartFindLine(cart, productVariantId) {
for (var _i = 0, _a = cart.lines.edges; _i < _a.length; _i++) {
var e = _a[_i];
if (e.node.merchandise.id == productVariantId) {
return e.node;
}
}
return null;
}
exports.cartFindLine = cartFindLine;
/**
* Turn a cart into checkout line items
* @param cart
*/
function cartToLineItems(cart) {
var lineItems = [];
if (cart) {
(0, graphql_1.forEachGraphQLList)(cart.lines, function (i) {
var l = {
variantId: i.merchandise.id,
quantity: i.quantity
};
lineItems.push(l);
});
}
return lineItems;
}
exports.cartToLineItems = cartToLineItems;
/**
* Notify users that someone added a product to their cart
* @param params
*/
function cartNotifyProductAdded(params) {
return function (dispatch) {
return dispatch((0, api_1.post)({
url: '/shop/cart/notify-product-added',
parameters: __assign({}, params)
}));
};
}
exports.cartNotifyProductAdded = cartNotifyProductAdded;
//# sourceMappingURL=index.js.map