4
0
forked from crowetic/commerce

98 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-09-30 21:08:25 -05:00
import { CommerceAPIConfig } from 'lib/commerce/api';
import { GetAllProductsQueryVariables } from '../schema';
import fetchAPI from './utils/fetch-api';
2020-09-30 11:44:38 -05:00
2020-09-30 15:59:46 -05:00
export interface Images {
small?: ImageOptions;
medium?: ImageOptions;
large?: ImageOptions;
xl?: ImageOptions;
}
export interface ImageOptions {
width: number;
height?: number;
}
export type ProductImageVariables = Pick<
GetAllProductsQueryVariables,
| 'imgSmallWidth'
| 'imgSmallHeight'
| 'imgMediumWidth'
| 'imgMediumHeight'
| 'imgLargeWidth'
| 'imgLargeHeight'
| 'imgXLWidth'
| 'imgXLHeight'
>;
2020-10-01 15:16:23 -05:00
export interface BigcommerceConfigOptions extends CommerceAPIConfig {
2020-09-30 21:08:25 -05:00
images?: Images;
2020-10-01 15:16:23 -05:00
}
export interface BigcommerceConfig extends BigcommerceConfigOptions {
2020-09-30 21:08:25 -05:00
readonly imageVariables?: ProductImageVariables;
}
2020-09-30 11:44:38 -05:00
2020-09-30 21:08:25 -05:00
const API_URL = process.env.BIGCOMMERCE_STOREFRONT_API_URL;
const API_TOKEN = process.env.BIGCOMMERCE_STOREFRONT_API_TOKEN;
2020-09-30 11:44:38 -05:00
2020-09-30 21:08:25 -05:00
if (!API_URL) {
throw new Error(
`The environment variable BIGCOMMERCE_STOREFRONT_API_URL is missing and it's required to access your store`
);
}
2020-09-30 11:44:38 -05:00
2020-09-30 21:08:25 -05:00
if (!API_TOKEN) {
throw new Error(
`The environment variable BIGCOMMERCE_STOREFRONT_API_TOKEN is missing and it's required to access your store`
);
}
2020-09-30 12:32:46 -05:00
2020-10-01 15:16:23 -05:00
export class Config {
private config: BigcommerceConfig;
constructor(config: BigcommerceConfigOptions) {
this.config = {
...config,
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;
},
};
}
getConfig() {
return this.config;
}
setConfig(newConfig: Partial<BigcommerceConfig>) {
Object.assign(this.config, newConfig);
}
}
const config = new Config({
2020-09-30 21:08:25 -05:00
commerceUrl: API_URL,
apiToken: API_TOKEN,
fetch: fetchAPI,
2020-10-01 15:16:23 -05:00
});
2020-09-30 12:32:46 -05:00
2020-09-30 21:08:25 -05:00
export function getConfig() {
2020-10-01 15:16:23 -05:00
return config.getConfig();
2020-09-30 21:08:25 -05:00
}
2020-09-30 11:44:38 -05:00
2020-09-30 21:08:25 -05:00
export function setConfig(newConfig: Partial<BigcommerceConfig>) {
2020-10-01 15:16:23 -05:00
return config.setConfig(newConfig);
2020-09-30 11:44:38 -05:00
}