GunaTrika 82f14ef467 Enabling login
- Added moltin call from the server side
 - Set the cookie with customer tokens with btoa encoded
2021-07-20 15:47:38 +05:30

51 lines
1.3 KiB
TypeScript

import { Fetcher } from '@commerce/utils/types'
import { FetcherError } from '@commerce/utils/errors'
async function getText(res: Response) {
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 ({
url,
method = 'POST',
variables,
query,
body: bodyObj,
}) => {
const shopApiUrl =
process.env.NEXT_PUBLIC_ELASTICPATH_BASE
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)
}