UNPKG

woocommerce-rest-ts-api

Version:

WooCommerce REST API - Type Script Library

469 lines (468 loc) 13.1 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts import axios from "axios"; import crypto from "crypto"; import OAuth from "oauth-1.0a"; import Url from "url-parse"; var WooCommerceRestApi = class _WooCommerceRestApi { /** * Class constructor. * * @param {Object} opt */ constructor(opt) { this._opt = opt; if (!(this instanceof _WooCommerceRestApi)) { return new _WooCommerceRestApi(opt); } if (!this._opt.url || this._opt.url === "") { throw new OptionsException("url is required"); } if (!this._opt.consumerKey || this._opt.consumerKey === "") { throw new OptionsException("consumerKey is required"); } if (!this._opt.consumerSecret || this._opt.consumerSecret === "") { throw new OptionsException("consumerSecret is required"); } this._setDefaultsOptions(this._opt); } /** * Set default options * * @param {Object} opt */ _setDefaultsOptions(opt) { this._opt.wpAPIPrefix = opt.wpAPIPrefix || "wp-json"; this._opt.version = opt.version || "wc/v3"; this._opt.isHttps = /^https/i.test(this._opt.url); this._opt.encoding = opt.encoding || "utf-8"; this._opt.queryStringAuth = opt.queryStringAuth || false; this._opt.classVersion = "0.0.2"; } /** * Parse params to object. * * @param {Object} params * @param {Object} query * @return {Object} IWooRestApiQuery */ // _parseParamsObject<T>(params: Record<string, T>, query: Record<string, any>): IWooRestApiQuery { // for (const key in params) { // if (typeof params[key] === "object") { // // If the value is an object, loop through it and add it to the query object // for (const subKey in params[key]) { // query[key + "[" + subKey + "]"] = params[key][subKey]; // } // } else { // query[key] = params[key]; // If the value is not an object, add it to the query object // } // } // return query; // Return the query object // } /** * Normalize query string for oAuth 1.0a * Depends on the _parseParamsObject method * * @param {String} url * @param {Object} params * * @return {String} */ _normalizeQueryString(url, params) { if (url.indexOf("?") === -1 && Object.keys(params).length === 0) { return url; } const query = new Url(url, true).query; const values = []; let queryString = ""; for (const key in query) { values.push(key); } values.sort(); for (const i in values) { if (queryString.length) queryString += "&"; queryString += encodeURIComponent(values[i]) + "=" + encodeURIComponent(query[values[i]]); } queryString = queryString.replace(/%5B/g, "[").replace(/%5D/g, "]"); const urlObject = url.split("?")[0] + "?" + queryString; return urlObject; } /** * Get URL * * @param {String} endpoint * @param {Object} params * * @return {String} */ _getUrl(endpoint, params) { const api = this._opt.wpAPIPrefix + "/"; let url = this._opt.url.slice(-1) === "/" ? this._opt.url : this._opt.url + "/"; url = url + api + this._opt.version + "/" + endpoint; if (params.id) { url = url + "/" + params.id; delete params.id; } if (Object.keys(params).length !== 0) { const queryString = Object.entries(params).map( ([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}` ).join("&"); url = `${url}?${queryString}`; } if (this._opt.port) { const hostname = new Url(url).hostname; url = url.replace(hostname, hostname + ":" + this._opt.port); } return url; } /** * Create Hmac was deprecated fot this version at 16.11.2022 * Get OAuth 1.0a since it is mandatory for WooCommerce REST API * You must use OAuth 1.0a "one-legged" authentication to ensure REST API credentials cannot be intercepted by an attacker. * Reference: https://woocommerce.github.io/woocommerce-rest-api-docs/#authentication-over-http * @return {Object} */ _getOAuth() { const data = { consumer: { key: this._opt.consumerKey, secret: this._opt.consumerSecret }, signature_method: "HMAC-SHA256", hash_function: (base, key) => { return crypto.createHmac("sha256", key).update(base).digest("base64"); } }; return new OAuth(data); } /** * Axios request * Mount the options to send to axios and send the request. * * @param {String} method * @param {String} endpoint * @param {Object} data * @param {Object} params * * @return {Object} */ _request(_0, _1, _2) { return __async(this, arguments, function* (method, endpoint, data, params = {}) { var _a; const url = this._getUrl(endpoint, params); const header = { Accept: "application/json" }; if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") { header["User-Agent"] = "WooCommerce REST API - TS Client/" + this._opt.classVersion; } let options = { url, method, responseEncoding: this._opt.encoding, timeout: this._opt.timeout, responseType: "json", headers: __spreadValues({}, header), params: {}, data: data ? JSON.stringify(data) : null }; if (this._opt.isHttps) { if (this._opt.queryStringAuth) { options.params = { consumer_key: this._opt.consumerKey, consumer_secret: this._opt.consumerSecret }; } else { options.auth = { username: this._opt.consumerKey, password: this._opt.consumerSecret }; } options.params = __spreadValues(__spreadValues({}, options.params), params); } else { options.params = this._getOAuth().authorize({ url, method }); } if (options.data) { options.headers = __spreadProps(__spreadValues({}, header), { "Content-Type": `application/json; charset=${this._opt.encoding}` }); } options = __spreadValues(__spreadValues({}, options), this._opt.axiosConfig); try { return yield axios(options); } catch (error) { if (error.response) { const apiError = new WooCommerceApiError( ((_a = error.response.data) == null ? void 0 : _a.message) || error.message || "API request failed", error.response.status, error.response.data, endpoint ); throw apiError; } else if (error.request) { throw new WooCommerceApiError( "Network error: No response received from server", 0, null, endpoint ); } else { throw new WooCommerceApiError( `Request setup error: ${error.message}`, 0, null, endpoint ); } } }); } /** * GET requests * * @param {String} endpoint * @param {Object} params * * @return {Object} */ get(endpoint, params) { return this._request("GET", endpoint, void 0, params).then( (response) => ({ data: response.data, status: response.status, statusText: response.statusText, headers: response.headers }) ); } /** * POST requests * * @param {String} endpoint * @param {Object} data * @param {Object} params * * @return {Object} */ post(endpoint, data, params) { return this._request("POST", endpoint, data, params).then((response) => ({ data: response.data, status: response.status, statusText: response.statusText, headers: response.headers })); } /** * PUT requests * * @param {String} endpoint * @param {Object} data * @param {Object} params * * @return {Object} */ put(endpoint, data, params) { return this._request("PUT", endpoint, data, params).then((response) => ({ data: response.data, status: response.status, statusText: response.statusText, headers: response.headers })); } /** * DELETE requests * * @param {String} endpoint * @param {Object} params * @param {Object} params * * @return {Object} */ delete(endpoint, data, params) { return this._request("DELETE", endpoint, data, params).then((response) => ({ data: response.data, status: response.status, statusText: response.statusText, headers: response.headers })); } /** * OPTIONS requests * * @param {String} endpoint * @param {Object} params * * @return {Object} */ options(endpoint, params) { return this._request("OPTIONS", endpoint, {}, params).then((response) => ({ data: response.data, status: response.status, statusText: response.statusText, headers: response.headers })); } // Convenience methods with proper typing /** * Get all products with proper typing */ getProducts(params) { return __async(this, null, function* () { return this.get("products", params); }); } /** * Get a single product by ID */ getProduct(id) { return __async(this, null, function* () { return this.get("products", { id }); }); } /** * Create a new product */ createProduct(productData) { return __async(this, null, function* () { return this.post("products", productData); }); } /** * Update an existing product */ updateProduct(id, productData) { return __async(this, null, function* () { return this.put("products", productData, { id }); }); } /** * Get all orders with proper typing */ getOrders(params) { return __async(this, null, function* () { return this.get("orders", params); }); } /** * Get a single order by ID */ getOrder(id) { return __async(this, null, function* () { return this.get("orders", { id }); }); } /** * Create a new order */ createOrder(orderData) { return __async(this, null, function* () { return this.post("orders", orderData); }); } /** * Get all customers with proper typing */ getCustomers(params) { return __async(this, null, function* () { return this.get("customers", params); }); } /** * Get a single customer by ID */ getCustomer(id) { return __async(this, null, function* () { return this.get("customers", { id }); }); } /** * Get all coupons with proper typing */ getCoupons(params) { return __async(this, null, function* () { return this.get("coupons", params); }); } /** * Get system status */ getSystemStatus() { return __async(this, null, function* () { return this.get("system_status"); }); } }; var WooCommerceApiError = class extends Error { constructor(message, statusCode, response, endpoint) { super(message); this.statusCode = statusCode; this.response = response; this.endpoint = endpoint; this.name = "WooCommerceApiError"; } }; var AuthenticationError = class extends WooCommerceApiError { constructor(message = "Authentication failed") { super(message, 401); this.name = "AuthenticationError"; } }; var OptionsException = class { /** * Constructor. * * @param {String} message */ constructor(message) { this.name = "Options Error"; this.message = message; } }; export { AuthenticationError, OptionsException, WooCommerceApiError, WooCommerceRestApi as default }; //# sourceMappingURL=index.mjs.map