Skip to content

Commit

Permalink
Merge pull request #49 from curiosta/feat/add-product-sync
Browse files Browse the repository at this point in the history
fix: sheets api issue
  • Loading branch information
Labham-Jain authored Nov 2, 2023
2 parents ffb2f78 + 36613c9 commit 0899e26
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 21 deletions.
Binary file modified dump.rdb
Binary file not shown.
7 changes: 7 additions & 0 deletions global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { CookieJar } from 'tough-cookie';

declare module 'axios' {
interface AxiosRequestConfig {
jar?: CookieJar;
}
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"@types/node-fetch": "^2.6.6",
"async": "^3.2.4",
"axios": "^1.5.1",
"axios-cookiejar-support": "^4.0.7",
"babel-preset-medusa-package": "^1.1.19",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
Expand All @@ -61,6 +62,7 @@
"nanoid": "^5.0.1",
"node-fetch": "2",
"openai": "^3.2.1",
"tough-cookie": "^4.1.3",
"typeorm": "^0.3.16",
"ulid": "^2.3.0"
},
Expand Down Expand Up @@ -112,4 +114,4 @@
"engines": {
"node": ">=18.0.0"
}
}
}
1 change: 1 addition & 0 deletions src/api/routes/admin/sheets/sync-products.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const SheetsSyncProductsRouter = (router: Router) => {
}

try {

const products = await productService.list({}, { relations: ['categories', 'variants'] })

googleSheetService.syncProducts(products)
Expand Down
6 changes: 3 additions & 3 deletions src/services/google-sheet-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ class GoogleSheetAPIService extends TransactionBaseService {
rowNumber: index + 2 // 1 for index, 2nd for header. so adding 2.
};

if (!row[1] || !row[2]) {
// if no title is available only then skip that row
if (!row[1]) {
return;
}

Expand Down Expand Up @@ -114,7 +115,6 @@ class GoogleSheetAPIService extends TransactionBaseService {
}

async syncProducts(products: Product[]) {

Promise.all(products.map(async (product) => {
const location = product.categories?.filter(c => c.handle.startsWith('loc:'))[0];
const category = product.categories?.filter(c => !c.handle.startsWith('loc:'))[0];
Expand All @@ -140,7 +140,7 @@ class GoogleSheetAPIService extends TransactionBaseService {

// Stocks

product.variants?.[0].inventory_quantity || ''
product.variants?.[0]?.inventory_quantity || ''
]
})).then(async (sheetProducts) => {
const response = await this.sheets.spreadsheets.values.get({
Expand Down
39 changes: 22 additions & 17 deletions src/services/product.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { ProductService as BaseProductService, Product, ProductVariantService } from "@medusajs/medusa";
import { CreateProductInput, FindProductConfig, UpdateProductInput } from "@medusajs/medusa/dist/types/product";
import axios from 'axios';
import { CreateProductInput, UpdateProductInput } from "@medusajs/medusa/dist/types/product";
import axios, { Axios } from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';

class ProductService extends BaseProductService {
productVariantService: ProductVariantService;
base_url?: string | null;
token?: string;
selfServiceClient: Axios

credentials: {
email?: string | null;
password?: string | null;
Expand All @@ -14,40 +18,45 @@ class ProductService extends BaseProductService {
constructor(container) {
super(container);
this.productVariantService = container.productVariantService as ProductVariantService
this.base_url = process.env.BASE_URL;
this.base_url = process.env.BASE_URL
this.credentials = {
email: process.env.MEDUSA_BACKEND_SERVICE_EMAIL,
password: process.env.MEDUSA_BACKEND_SERVICE_PASSWORD
}
}

private async loginAdmin() {
if (!this.credentials.email || !this.credentials.password) {
throw new Error('Backend service credentials are missing!. Please add them or contact administrator!')
}

if (!this.base_url) {
throw new Error('Backend service host url is missing!. Please add them or contact administrator!')
}

if (!this.credentials.email || !this.credentials.password) {
throw new Error('Backend service credentials are missing!. Please add them or contact administrator!')
}
this.selfServiceClient = wrapper(axios.create({
baseURL: this.base_url,
jar: new CookieJar()
}))
}

private async loginAdmin() {



try {
// login system user to admin
const result = await axios.post(`${process.env.BASE_URL}/admin/auth/token`, {
await this.selfServiceClient.post(`${process.env.BASE_URL}/admin/auth`, {
'email': this.credentials.email,
'password': this.credentials.password
});

this.token = result.data?.access_token;

} catch (error) {
console.log(error);
throw new Error('Failed to login as backend service!. ensure credentials are correct and stable network connection!')
}
}

private async createProductWithFetch(product: CreateProductInput) {
const response = await axios.post<{ product: Product }>(`${this.base_url}/admin/products`, product, {
const response = await this.selfServiceClient.post<{ product: Product }>(`${this.base_url}/admin/products`, product, {
headers: {
'Authorization': `Bearer ${this.token}`
}
Expand All @@ -56,11 +65,7 @@ class ProductService extends BaseProductService {
}

private async updateProductWithFetch(id: string, product: UpdateProductInput) {
const response = await axios.post<{ product: Product }>(`${this.base_url}/admin/products/${id}`, product, {
headers: {
'Authorization': `Bearer ${this.token}`
}
});
const response = await this.selfServiceClient.post<{ product: Product }>(`${this.base_url}/admin/products/${id}`, product);
return response.data;
}

Expand Down

0 comments on commit 0899e26

Please sign in to comment.