Use moltin sdk in fetcher

This commit is contained in:
GunaTrika 2021-09-28 10:28:21 +05:30
parent f6e59f412e
commit ef2bd1fdcb

View File

@ -1,50 +1,39 @@
import { Fetcher } from '@commerce/utils/types' import { Fetcher } from './utils/types'
import { FetcherError } from '@commerce/utils/errors' import { FetcherError } from '@commerce/utils/errors'
import { gateway as MoltinGateway, Moltin } from '@moltin/sdk';
async function getText(res: Response) { import epClient from './utils/ep-client'
try {
return (await res.text()) || res.statusText
} catch (error) {
return res.statusText
}
}
async function getError(res: Response) {
if (res.headers.get('Content-Type')?.includes('application/json')) {
const data = await res.json()
return new FetcherError({ errors: data.errors, status: res.status })
}
return new FetcherError({ message: await getText(res), status: res.status })
}
export const fetcher: Fetcher = async ({ export const fetcher: Fetcher = async ({
url, url,
method = 'POST', method = 'POST',
variables, variables:{params}
query,
body: bodyObj,
}) => { }) => {
const shopApiUrl = if(url && method) {
process.env.NEXT_PUBLIC_ELASTICPATH_BASE try {
if (!shopApiUrl) {
throw new Error(
'The Vendure Shop API url has not been provided. Please define NEXT_PUBLIC_VENDURE_SHOP_API_URL in .env.local'
)
}
const hasBody = Boolean(variables || query)
const body = hasBody ? JSON.stringify(variables) : undefined
const headers = hasBody ? { 'Content-Type': 'application/json' } : undefined
const res = await fetch(""+url, {
method,
body,
headers,
credentials: 'include',
})
if (res.ok) {
const { data } = await res.json()
return data
}
throw await getError(res) let res = await epClient[url][method](...params);
if(res.errors && res.errors > 0) {
let error = res.errors[0];
throw new FetcherError({
message: error.detail,
status: error.status
});
}
return res;
} catch(err) {
console.log(err);
throw new FetcherError({
message: "Malformed request",
status: 400
});
}
}
throw new FetcherError({
message: "Malformed request",
status: 400
});
} }