Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@imagination-media/magento-api-rest",
"version": "3.0.8",
"version": "3.0.9",
"description": "Magento API wrapper",
"main": "lib/index.js",
"files": [
Expand Down
139 changes: 79 additions & 60 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,61 +1,79 @@
import axios from 'axios';
import crypto from 'crypto';
import OAuth from 'oauth-1.0a';
import axios from "axios"
import crypto from "crypto"
import OAuth from "oauth-1.0a"

class MagentoApi {
private url: string;
private consumerKey: string;
private consumerSecret: string;
private accessToken: string;
private tokenSecret: string;
private magentoVersion: string|null|undefined;
private url: string
private consumerKey: string
private consumerSecret: string
private accessToken: string
private tokenSecret: string
private magentoVersion: string | null | undefined

/**
* Constructor
* @param params object
*/
constructor(params: MagentoApiParams) {
this.url = params.url;
this.consumerKey = params.consumerKey;
this.consumerSecret = params.consumerSecret;
this.accessToken = params.accessToken;
this.tokenSecret = params.tokenSecret;
this.magentoVersion = params.magentoVersion;
this.url = params.url
this.consumerKey = params.consumerKey
this.consumerSecret = params.consumerSecret
this.accessToken = params.accessToken
this.tokenSecret = params.tokenSecret
this.magentoVersion = params.magentoVersion
}

/**
* Parse an Object to queryString
* @returns string
*/
parseQueryString(obj: any, prefix: string | null = null): string {
let str = [], p: any
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p]
str.push((v !== null && typeof v === "object") ?
this.parseQueryString(v, k) :
k + "=" + v)
}
}
return str.join("&")
}

/**
* Get the headers for the request
* @returns Header
*/
getHeaders(url: string, method: "GET"|"POST"|"PUT"|"DELETE"): Header {
getHeaders(url: string, method: "GET" | "POST" | "PUT" | "DELETE"): Header {
// Initialize OAuth
const oauth = new OAuth({
consumer: {
key: this.consumerKey,
secret: this.consumerSecret,
},
signature_method: 'HMAC-SHA256',
signature_method: "HMAC-SHA256",
hash_function(base_string, key) {
return crypto
.createHmac('sha256', key)
.createHmac("sha256", key)
.update(base_string)
.digest('base64');
.digest("base64")
},
})

// Token (from your Magento installation)
const token = {
key: this.accessToken,
secret: this.tokenSecret,
};
}

const requestData = {
url,
method
};
}

let header = {
'Content-Type': 'application/json'
"Content-Type": "application/json"
}

const oauthHeader = oauth.toHeader(oauth.authorize(requestData, token))
Expand All @@ -71,9 +89,9 @@ class MagentoApi {
* @returns string
*/
getUrl(): string {
const version = this.magentoVersion ? this.magentoVersion : 'V1';
const version = this.magentoVersion ? this.magentoVersion : "V1"

return `${this.url}/rest/${version}/`;
return `${this.url}/rest/${version}/`
}

/**
Expand All @@ -82,24 +100,25 @@ class MagentoApi {
* @param data any
* @returns Promise<any>
*/
async get (path: string, data: any|null = null): Promise<any> {
async get(path: string, data: any | null = null): Promise<any> {
try {
const url = `${this.getUrl()}${path}`;
let url = `${this.getUrl()}${path}`

if (data) {
let params = {
searchCriteria: data
}
url += `?${this.parseQueryString(params)}`
return await axios.get(url, {
headers: this.getHeaders(url, "GET") as any,
params: {
searchCriteria: data
}
});
})
} else {
return await axios.get(`${this.getUrl()}${path}`, {
headers: this.getHeaders(url, "GET") as any
});
})
}
} catch (error:any) {
console.error(error);
} catch (error: any) {
console.error(error)
}
}

Expand All @@ -109,14 +128,14 @@ class MagentoApi {
* @param data any
* @returns Promise<any>
*/
async post (path: string, data: any): Promise<any> {
async post(path: string, data: any): Promise<any> {
try {
const url = `${this.getUrl()}${path}`;
const url = `${this.getUrl()}${path}`
return await axios.post(url, data, {
headers: this.getHeaders(url, "POST") as any
});
} catch (error:any) {
console.error(error);
})
} catch (error: any) {
console.error(error)
}
}

Expand All @@ -126,14 +145,14 @@ class MagentoApi {
* @param data any
* @returns Promise<any>
*/
async put (path: string, data: any): Promise<any> {
async put(path: string, data: any): Promise<any> {
try {
const url = `${this.getUrl()}${path}`;
const url = `${this.getUrl()}${path}`
return await axios.put(url, data, {
headers: this.getHeaders(url, "PUT") as any
});
} catch (error:any) {
console.error(error);
})
} catch (error: any) {
console.error(error)
}
}

Expand All @@ -142,34 +161,34 @@ class MagentoApi {
* @param path string
* @returns Promise<any>
*/
async delete (path: string): Promise<any> {
async delete(path: string): Promise<any> {
try {
const url = `${this.getUrl()}${path}`;
const url = `${this.getUrl()}${path}`
return await axios.delete(url, {
headers: this.getHeaders(url, "DELETE") as any
});
} catch (error:any) {
console.error(error);
})
} catch (error: any) {
console.error(error)
}
}

/**
* Set the default values for the Magento API
* @param params object
*/
_setDefaults (params: MagentoApiParams) {
this.url = params.url;
this.consumerKey = params.consumerKey;
this.consumerSecret = params.consumerSecret;
this.accessToken = params.accessToken;
this.tokenSecret = params.tokenSecret;
this.magentoVersion = params.magentoVersion;
_setDefaults(params: MagentoApiParams) {
this.url = params.url
this.consumerKey = params.consumerKey
this.consumerSecret = params.consumerSecret
this.accessToken = params.accessToken
this.tokenSecret = params.tokenSecret
this.magentoVersion = params.magentoVersion
}
}

interface Header {
'Content-Type': string,
'Authorization': string
"Content-Type": string,
"Authorization": string
}

interface MagentoApiParams {
Expand All @@ -178,7 +197,7 @@ interface MagentoApiParams {
consumerSecret: string,
accessToken: string,
tokenSecret: string,
magentoVersion?: string|null|undefined,
magentoVersion?: string | null | undefined,
}

export default MagentoApi;
export default MagentoApi
24 changes: 12 additions & 12 deletions test/catalog/product/get.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { default as MagentoApi } from '../../../src/index';
import { default as MagentoApi } from "../../../src/index";

(async () => {
let client = new MagentoApi({
'url': '',
'consumerKey': '',
'consumerSecret': '',
'accessToken': '',
'tokenSecret': ''
});
"url": "",
"consumerKey": "",
"consumerSecret": "",
"accessToken": "",
"tokenSecret": ""
})

let sku = "65-813";
let sku = "65-813"

try {
let response = await client.get(`products/${sku}`);
console.log(JSON.stringify(response.data));
let response = await client.get(`products/${sku}`)
console.log(JSON.stringify(response.data))
} catch (e) {
console.log(e);
console.log(e)
}
})();
})()
33 changes: 33 additions & 0 deletions test/customer/pull.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { default as MagentoApi } from "../../src/index";

(async () => {
let client = new MagentoApi({
url: "baseUrl",
consumerKey: "customerKey",
consumerSecret: "consumerSecret",
accessToken: "accessToken",
tokenSecret: "tokenSecret",
magentoVersion: "V1"
})

let params = {
"filter_groups": [{
"filters": [{
"field": "created_at",
"value": "2024-03-12 0:00:00",
"condition_type": "gteq"
}]
}],
"sortOrders": [{
"field": "entity_id",
"direction": "asc"
}]
}

try {
let response = await client.get("customers/search", params)
console.log(JSON.stringify(response.data))
} catch (e) {
console.log(e)
}
})()
28 changes: 14 additions & 14 deletions test/inventory/push.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import { default as MagentoApi } from '../../src/index';
import { default as MagentoApi } from "../../src/index";

(async () => {
let client = new MagentoApi({
url: 'https://portal.satco.com/',
consumerKey: '',
consumerSecret: '',
accessToken: '',
tokenSecret: '',
magentoVersion: 'async/V1'
});
url: "https://portal.satco.com/",
consumerKey: "",
consumerSecret: "",
accessToken: "",
tokenSecret: "",
magentoVersion: "async/V1"
})

let data = [
{"sku":"96-323","source_code":"10","quantity":0,"status":0}
];
]

try {
let response = await client.post(`inventory/source-items`, {
let response = await client.post("inventory/source-items", {
"sourceItems": data
});
console.log(JSON.stringify(response.data));
})
console.log(JSON.stringify(response.data))
} catch (e) {
console.log(e);
console.log(e)
}
})();
})()