Use functions instead of a class

This commit is contained in:
Luis Alvarez 2020-09-30 21:08:25 -05:00
parent e242525476
commit 2971b4f802
7 changed files with 141 additions and 122 deletions

View File

@ -1,20 +1,6 @@
import {
CommerceAPI,
CommerceAPIOptions,
CommerceAPIFetchOptions,
} from 'lib/commerce/api';
import { GetAllProductsQuery, GetAllProductsQueryVariables } 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;
}
import { CommerceAPIConfig } from 'lib/commerce/api';
import { GetAllProductsQueryVariables } from '../schema';
import fetchAPI from './utils/fetch-api';
export interface Images {
small?: ImageOptions;
@ -28,10 +14,6 @@ export interface ImageOptions {
height?: number;
}
export interface BigcommerceAPIOptions extends CommerceAPIOptions {
images?: Images;
}
export type ProductImageVariables = Pick<
GetAllProductsQueryVariables,
| 'imgSmallWidth'
@ -44,83 +26,51 @@ export type ProductImageVariables = Pick<
| 'imgXLHeight'
>;
export type ProductVariables = Images &
Omit<GetAllProductsQueryVariables, keyof ProductImageVariables>;
export default class BigcommerceAPI implements CommerceAPI {
commerceUrl: string;
apiToken: string;
imageVariables?: ProductImageVariables;
constructor({ commerceUrl, apiToken, images }: BigcommerceAPIOptions) {
this.commerceUrl = commerceUrl;
this.apiToken = apiToken;
this.imageVariables = {
imgSmallWidth: images?.small?.width,
imgSmallHeight: images?.small?.height,
imgMediumWidth: images?.medium?.height,
imgMediumHeight: images?.medium?.height,
imgLargeWidth: images?.large?.height,
imgLargeHeight: images?.large?.height,
imgXLWidth: images?.xl?.height,
imgXLHeight: images?.xl?.height,
};
}
async fetch<Q, V = any>(
query: string,
{ variables, preview }: CommerceAPIFetchOptions<V> = {}
): Promise<Q> {
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, V = any>(opts: {
query: string;
variables?: V;
}): Promise<GetAllProductsResult<T>>;
async getAllProducts(opts?: {
query?: string;
variables?: ProductVariables;
}): Promise<GetAllProductsResult<GetAllProductsQuery>>;
async getAllProducts({
query = getAllProductsQuery,
variables: vars,
}: {
query?: string;
variables?: ProductVariables;
} = {}): Promise<
GetAllProductsResult<RecursivePartial<GetAllProductsQuery>>
> {
const variables: GetAllProductsQueryVariables = {
...this.imageVariables,
...vars,
};
const data = await this.fetch<RecursivePartial<GetAllProductsQuery>>(
query,
{ variables }
);
return {
products: data?.site?.products?.edges,
};
}
export interface BigcommerceConfig extends CommerceAPIConfig {
images?: Images;
readonly imageVariables?: ProductImageVariables;
}
const API_URL = process.env.BIGCOMMERCE_STOREFRONT_API_URL;
const API_TOKEN = process.env.BIGCOMMERCE_STOREFRONT_API_TOKEN;
if (!API_URL) {
throw new Error(
`The environment variable BIGCOMMERCE_STOREFRONT_API_URL is missing and it's required to access your store`
);
}
if (!API_TOKEN) {
throw new Error(
`The environment variable BIGCOMMERCE_STOREFRONT_API_TOKEN is missing and it's required to access your store`
);
}
const config: BigcommerceConfig = {
commerceUrl: API_URL,
apiToken: API_TOKEN,
fetch: fetchAPI,
get imageVariables() {
const { images } = this;
return images
? {
imgSmallWidth: images.small?.width,
imgSmallHeight: images.small?.height,
imgMediumWidth: images.medium?.height,
imgMediumHeight: images.medium?.height,
imgLargeWidth: images.large?.height,
imgLargeHeight: images.large?.height,
imgXLWidth: images.xl?.height,
imgXLHeight: images.xl?.height,
}
: undefined;
},
};
export function getConfig() {
return config;
}
export function setConfig(newConfig: Partial<BigcommerceConfig>) {
Object.assign(config, newConfig);
}

View File

@ -1,3 +1,10 @@
import {
GetAllProductsQuery,
GetAllProductsQueryVariables,
} from 'lib/bigcommerce/schema';
import { getConfig, Images, ProductImageVariables } from '..';
import { RecursivePartial } from '../types';
export const getAllProductsQuery = /* GraphQL */ `
query getAllProducts(
$first: Int = 10
@ -94,3 +101,46 @@ export const getAllProductsQuery = /* GraphQL */ `
}
}
`;
export interface GetAllProductsResult<T> {
products: T extends GetAllProductsQuery
? T['site']['products']['edges']
: unknown;
}
export type ProductVariables = Images &
Omit<GetAllProductsQueryVariables, keyof ProductImageVariables>;
async function getAllProducts<T, V = any>(opts: {
query: string;
variables?: V;
}): Promise<GetAllProductsResult<T>>;
async function getAllProducts(opts?: {
query?: string;
variables?: ProductVariables;
}): Promise<GetAllProductsResult<GetAllProductsQuery>>;
async function getAllProducts({
query = getAllProductsQuery,
variables: vars,
}: {
query?: string;
variables?: ProductVariables;
} = {}): Promise<GetAllProductsResult<RecursivePartial<GetAllProductsQuery>>> {
const config = getConfig();
const variables: GetAllProductsQueryVariables = {
...config.imageVariables,
...vars,
};
const data = await config.fetch<RecursivePartial<GetAllProductsQuery>>(
query,
{ variables }
);
return {
products: data?.site?.products?.edges,
};
}
export default getAllProducts;

View File

@ -0,0 +1,3 @@
export type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};

View File

@ -0,0 +1,27 @@
import { CommerceAPIFetchOptions } from 'lib/commerce/api';
import { getConfig } from '..';
export default async function fetchAPI<Q, V = any>(
query: string,
{ variables, preview }: CommerceAPIFetchOptions<V> = {}
): Promise<Q> {
const config = getConfig();
const res = await fetch(config.commerceUrl + (preview ? '/preview' : ''), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.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;
}

View File

@ -1,9 +0,0 @@
import BigcommerceAPI from './bigcommerce/api';
const API_URL = process.env.NEXT_EXAMPLE_BIGCOMMERCE_STOREFRONT_API_URL!;
const API_TOKEN = process.env.NEXT_EXAMPLE_BIGCOMMERCE_STOREFRONT_API_TOKEN!;
export const commerce = new BigcommerceAPI({
commerceUrl: API_URL,
apiToken: API_TOKEN,
});

View File

@ -1,6 +1,10 @@
export interface CommerceAPIOptions {
export interface CommerceAPIConfig {
commerceUrl: string;
apiToken: string;
fetch<Q, V = any>(
query: string,
queryData?: CommerceAPIFetchOptions<V>
): Promise<Q>;
}
export interface CommerceAPIFetchOptions<V> {
@ -8,14 +12,8 @@ export interface CommerceAPIFetchOptions<V> {
preview?: boolean;
}
export interface CommerceAPI {
commerceUrl: string;
apiToken: string;
// TODO: define interfaces for all the available operations
fetch<Q, V = any>(
query: string,
queryData?: CommerceAPIFetchOptions<V>
): Promise<Q>;
getAllProducts(options?: { query: string }): Promise<any>;
}
// export interface CommerceAPI {
// getAllProducts(options?: { query: string }): Promise<any>;
// }

View File

@ -1,9 +1,9 @@
import { GetStaticPropsContext, InferGetStaticPropsType } from 'next';
import { commerce } from 'lib/commerce-api';
import getAllProducts from 'lib/bigcommerce/api/operations/get-all-products';
import { Layout } from '@components/core';
export async function getStaticProps({ preview }: GetStaticPropsContext) {
const { products } = await commerce.getAllProducts();
const { products } = await getAllProducts();
return {
props: { products },