Skip to content

Commit

Permalink
v1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
allanvb committed Apr 13, 2023
0 parents commit 17f4317
Show file tree
Hide file tree
Showing 26 changed files with 943 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
dist/
package-lock.json
.idea/
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2023 MerchOne

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11 changes: 11 additions & 0 deletions fixmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
cat >dist/cjs/package.json <<!EOF
{
"type": "commonjs"
}
!EOF

cat >dist/esm/package.json <<!EOF
{
"type": "module"
}
!EOF
56 changes: 56 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "@merch-one/api",
"description": "JavaScript SDK for MerchOne API integration",
"homepage": "https://github.com/merch-one/js-api-sdk#readme",
"author": "The Customization Group",
"license": "MIT",
"version": "1.0.0",
"scripts": {
"prebuild": "rm -rf ./dist && tslint -p tsconfig.json --fix",
"build": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json",
"postbuild": "cp package.json dist/package.json && ./fixmodules && tsc-alias --dir dist/cjs -p tsconfig.cjs.json && tsc-alias --dir dist/esm -p tsconfig.esm.json && tsc-alias --dir dist/types && ts-add-js-extension add --dir=dist",
"lint": "tslint -p tsconfig.json"
},
"repository": {
"type": "git",
"url": "https://github.com/merch-one/js-api-sdk.git"
},
"files": [
"dist/*/**",
"LICENSE",
"readme.md"
],
"keywords": [
"api",
"api-client",
"api-library",
"printondemand",
"merchone",
"merchone-api"
],
"devDependencies": {
"@types/node": "^18.15.11",
"ts-add-js-extension": "^1.3.3",
"tsc-alias": "^1.8.5",
"tslint": "^6.1.3",
"typescript": "^5.0.3"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"types": "./index.d.ts",
"exports": {
".": {
"types": "./dist/types/index.js",
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js",
"default": "./dist/esm/index.js"
}
},
"typesVersions": {
">=4.2": {
"*": [
"types/*"
]
}
}
}
136 changes: 136 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<h2 align="center">
JavaScript SDK for MerchOne API integration
</h2>

<p align="center">
<a href="https://www.npmjs.com/package/@merch-one/api"><img src="https://img.shields.io/npm/v/@merch-one/api?color=orange&style=flat-square" alt="NPM Version"></a>
<a href="https://www.npmjs.com/package/@merch-one/api"><img src="https://img.shields.io/npm/l/@merch-one/api?color=brightgreen&style=flat-square" alt="License"></a>
<a href="https://www.npmjs.com/package/@merch-one/api"><img src="https://img.shields.io/github/last-commit/merch-one/js-api?color=blue&style=flat-square" alt="GitHub last commit"></a>
</p>

This package provide a set of tools that allow developers to easily integrate with MerchOne API.

## Installation
```shell
npm install @merch-one/api
```

## Overview

- [Introduction](#introduction)
- [Basic Usage](#basic-usage)
- [Helpers](#helpers)
- [Exceptions](#exceptions)

---

### Introduction
**Client provide 3 different API's to interact with.**
- Catalog API
- Orders API
- Shipping API

**To get the list of available endpoints, please check
[MerchOne API Documentation](https://docs.merchone.com/api-reference)**

---

### Basic Usage

- Package exports 3 classes: `Client`, `MerchOneApi`, `OrderStatus`

**Create an instance of `Client`**

```javascript
// import ES module
import { Client } from '@merch-one/api';

// require CommonJS module
const { Client } = require('@merch-one/api');

const client = Client.make();

function doSomething() {
// authenticate client using credentials
client.auth(
'your-store-user',
'your-store-key'
)

// or authenticate client using base64 encoded credentials
client.basicAuth(
btoa('your-store-user:your-store-key'),
)

/* Interact with Catalog API */
const catalogApi = client.catalog();

/* Interact with Orders API */
const ordersApi = client.orders();

/* Interact with Shipping API */
const shippingApi = client.shipping();

// switch API version you interact with
client.setVersion(version);

// get current API version
client.getVersion();
}

```

- The `Client` class accepts `version` parameter. Default value is set `beta`
- See [Helpers](#helpers) for available versions.
---

### Helpers

```js
// import ES module
import { MerchOneApi } from '@merch-one/api';

// require CommonJS module
const { MerchOneApi } = require('@merch-one/api');

// get the list of all available API versions
MerchOneApi.getVersions()
```

- Class OrderStatus provides a full list of Order statuses.

```js
// import ES module
import { OrderStatus } from '@merch-one/api';

// require CommonJS module
const { OrderStatus } = require('@merch-one/api');

// get the list of all available Order statuses
OrderStatus.all();
```


Check more in [MerchOne API Documentation](https://docs.merchone.com/api-reference/orders#order-status)

---

### Exceptions

The package can throw the following exceptions:

| Exception | Reason |
|---------------------------|-----------------------------------------------------|
| *MerchOneApiClientError* | Request is not correct or validation did not pass. |
| *MerchOneApiServerError* | A server error occurred. |
| *InvalidApiVersionError* | An invalid API version was provided to the Client. |
| *InvalidCredentialsError* | Invalid API credentials was provided to the Client. |


---
Under the hood, the package uses [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make requests.

Make sure you checked [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#browser_compatibility) before using it.

Also take note that Fetch API is available in Node.js only since version 17.5 with flag `--experimental-fetch`.
Starting from version 18.0, the flag is no longer required.
39 changes: 39 additions & 0 deletions src/clients/BaseApiClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Fetch from "@/http/Fetch";
import FetchResponse from "@/http/FetchResponse";
import MerchOneApiServerError from "@/errors/MerchOneApiServerError";
import MerchOneApiClientError from "@/errors/MerchOneApiClientError";
import InvalidCredentialsError from "@/errors/InvalidCredentialsError";

export default abstract class BaseApiClient {
protected httpClient: Fetch;

constructor(httpClient: Fetch) {
this.httpClient = httpClient;
}

protected request(method: string, path: string, data: any = {}, responseKey: string | null = "data"): Promise<any> {
return new Promise((resolve) => {
new Fetch(this.httpClient.defaults.baseURL, this.httpClient.defaults.headers)
.request(path, method, data)
.then((response: any) => resolve(response.json(responseKey)))
.catch(this.handleError);
});
}

private handleError = (response: FetchResponse) => {

if (response.serverError()) {
throw new MerchOneApiServerError(response.getMessage());
}

if (response.unauthorized()) {
throw new InvalidCredentialsError();
}

if (response.clientError()) {
throw new MerchOneApiClientError(response.getErrors());
}

return Promise.reject(response.getMessage());
}
}
20 changes: 20 additions & 0 deletions src/clients/beta/Catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import BaseApiClient from "@/clients/BaseApiClient";
import CatalogApi from "@/types/clients/CatalogApi";

export default class Catalog extends BaseApiClient implements CatalogApi {
public getProducts(): Promise<object> {
return this.request("get", "products");
}

public getProductVariants(productId: number): Promise<object> {
return this.request("get", `products/${productId}`);
}

public getVariantOptions(variantId: number): Promise<object> {
return this.request("get", `variants/${variantId}`);
}

public getVariantCombinations(variantId: number): Promise<object> {
return this.request("get", `variants/${variantId}/combinations`);
}
}
46 changes: 46 additions & 0 deletions src/clients/beta/Orders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import BaseApiClient from "@/clients/BaseApiClient";
import OrdersApi from "@/types/clients/OrdersApi";

export default class Orders extends BaseApiClient implements OrdersApi {
public all(page: number = 1): Promise<object> {
return new Promise(resolve => {
this.request("get", `orders?page=${page}`, {}, null)
.then((response) => {
resolve({
orders: response.data,
pagination: response.meta.pagination,
});
});
});
}

public create(order: object): Promise<object> {
return this.request("post", "/orders", order);
}

public get(orderId: string, usingExternalId: boolean = false): Promise<object> {
orderId = usingExternalId ? `@${orderId}` : orderId;

return this.request("get", `/orders/${orderId}`);
}

public cancel(orderId: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.request("delete", `/orders/${orderId}`)
.then(() => resolve(true))
.catch(() => reject(false));
});
}

public firstOrCreate(order: any, usingExternalId: boolean = true): Promise<object> {
const orderId = usingExternalId ? order.external_id : order.id;

return new Promise(resolve => {
this.get(orderId, usingExternalId)
.then((response) => resolve(response))
.catch(async () => {
await this.create(order);
});
});
}
}
31 changes: 31 additions & 0 deletions src/clients/beta/Shipping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import BaseApiClient from "@/clients/BaseApiClient";
import ShippingApi from "@/types/clients/ShippingApi";

export default class Shipping extends BaseApiClient implements ShippingApi {
public getRates(countryId: number, items: object[]): Promise<object> {
const body = {
shipping: {
country: countryId,
},
items
};

return this.request("post", "/shipping/rates", body);
}

public getTypes(): Promise<object> {
return this.request("get", "/shipping/types");
}

public getMethods(): Promise<object> {
return this.request("get", "/shipping/methods");
}

public getCountries(): Promise<object> {
return this.request("get", "/countries");
}

public getRegions(countryId: number): Promise<object> {
return this.request("get", `/regions/${countryId}`);
}
}
6 changes: 6 additions & 0 deletions src/errors/InvalidApiVersionError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default class InvalidApiVersionError extends Error {
constructor(message: string) {
super(message);
this.name = "InvalidApiVersionError";
}
}
6 changes: 6 additions & 0 deletions src/errors/InvalidCredentialsError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default class InvalidCredentialsError extends Error {
constructor() {
super("Invalid API credentials");
this.name = "InvalidApiCredentialsError";
}
}
6 changes: 6 additions & 0 deletions src/errors/MerchOneApiClientError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default class MerchOneApiClientError extends Error {
constructor(message: string) {
super(message);
this.name = "MerchOneApiClientError";
}
}
Loading

0 comments on commit 17f4317

Please sign in to comment.