4
0
forked from crowetic/commerce

72 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-09-30 11:44:38 -05:00
import {
CommerceAPI,
CommerceAPIOptions,
CommerceAPIFetchOptions,
} from 'lib/commerce/api';
import { GetAllProductsQuery } from '../schema';
import { getAllProductsQuery } from './operations/get-all-products';
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
export interface GetAllProductsResult<T> {
products: T extends GetAllProductsQuery
? T['site']['products']['edges']
: unknown;
}
export default class BigcommerceAPI implements CommerceAPI {
2020-09-30 12:32:46 -05:00
commerceUrl: string;
apiToken: string;
2020-09-30 11:44:38 -05:00
constructor({ commerceUrl, apiToken }: CommerceAPIOptions) {
this.commerceUrl = commerceUrl;
this.apiToken = apiToken;
}
async fetch<T>(
query: string,
{ variables, preview }: CommerceAPIFetchOptions = {}
): Promise<T> {
const res = await fetch(this.commerceUrl + (preview ? '/preview' : ''), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiToken}`,
},
body: JSON.stringify({
query,
variables,
}),
});
const json = await res.json();
if (json.errors) {
console.error(json.errors);
throw new Error('Failed to fetch API');
}
return json.data;
}
async getAllProducts<T>(opts: {
query: string;
}): Promise<GetAllProductsResult<T>>;
2020-09-30 12:32:46 -05:00
async getAllProducts(opts?: {
query?: string;
}): Promise<GetAllProductsResult<GetAllProductsQuery>>;
async getAllProducts({
query = getAllProductsQuery,
2020-09-30 11:44:38 -05:00
}: { query?: string } = {}): Promise<
2020-09-30 12:32:46 -05:00
GetAllProductsResult<RecursivePartial<GetAllProductsQuery>>
2020-09-30 11:44:38 -05:00
> {
2020-09-30 12:32:46 -05:00
const data = await this.fetch<RecursivePartial<GetAllProductsQuery>>(query);
2020-09-30 11:44:38 -05:00
return {
2020-09-30 12:32:46 -05:00
products: data?.site?.products?.edges,
2020-09-30 11:44:38 -05:00
};
}
}