Adding more types

This commit is contained in:
Luis Alvarez 2020-09-30 00:41:42 -05:00
parent 33cb4ea905
commit 7f6a8498cd
4 changed files with 61 additions and 5 deletions

View File

@ -1,11 +1,52 @@
import { CommerceAPI } from 'lib/commerce/api';
import {
CommerceAPI,
CommerceAPIOptions,
CommerceAPIFetchOptions,
} from 'lib/commerce/api';
import { GetAllProductsQuery } from '../schema';
import { getAllProductsQuery } from './queries/get-all-products';
import { getAllProductsQuery } from './operations/get-all-products';
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
export default class BigcommerceAPI implements CommerceAPI {
getAllProducts<T = GetAllProductsQuery>(
commerceUrl: string;
apiToken: string;
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 = GetAllProductsQuery>(
query: string = getAllProductsQuery
): Promise<T> {
return null as any;
const data = await this.fetch<RecursivePartial<GetAllProductsQuery>>(query);
return data as T;
}
}

View File

@ -1,4 +1,19 @@
export interface CommerceAPIOptions {
commerceUrl: string;
apiToken: string;
}
export interface CommerceAPIFetchOptions {
variables?: object;
preview?: boolean;
}
export interface CommerceAPI {
commerceUrl: string;
apiToken: string;
fetch<T>(query: string, queryData?: CommerceAPIFetchOptions): Promise<T>;
getAllProducts(query: string): Promise<any>;
}

View File

@ -5,7 +5,7 @@
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,