The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
import { createClient, InferClient, adminAuth } from '@mercurjs/client'
import { Routes } from '@mercurjs/core/_generated'
import config from 'virtual:mercur/config'
import { assetUrl } from '../../utils/asset-url'
import { clearAuthToken, getAuthHeaders } from './auth-token'
export const backendUrl = config.backendUrl ?? 'http://localhost:9000'
export const sdk: InferClient<Routes> = createClient({
baseUrl: backendUrl,
fetchOptions: {
credentials: 'omit',
},
auth: adminAuth(),
})
export const fetchQuery = async (
url: string,
{
method,
body,
query,
headers,
}: {
method: 'GET' | 'POST' | 'DELETE'
body?: object
query?: Record<string, string | number | object>
headers?: { [key: string]: string }
}
) => {
const params = Object.entries(query || {}).reduce((acc, [key, value]) => {
if (value !== null && value !== undefined && value !== '') {
if (Array.isArray(value)) {
const arrayParams = value
.map(
(item) =>
`${encodeURIComponent(key)}[]=${encodeURIComponent(item)}`
)
.join('&')
if (acc) {
acc += '&' + arrayParams
} else {
acc = arrayParams
}
} else {
const separator = acc ? '&' : ''
const serializedValue =
typeof value === 'object' ? JSON.stringify(value) : value
acc += `${separator}${encodeURIComponent(key)}=${encodeURIComponent(serializedValue)}`
}
}
return acc
}, '')
const response = await fetch(
`${backendUrl}${url}${params ? `?${params}` : ''}`,
{
method,
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
...(await getAuthHeaders()),
...headers,
},
body: body ? JSON.stringify(body) : null,
}
)
if (!response.ok) {
const errorData = await response.json()
if (response.status === 401) {
clearAuthToken()
window.location.href = `${assetUrl('/login')}?reason=Unauthorized`
return
}
const error = new Error(errorData.message || 'Server error')
; (error as Error & { status: number }).status = response.status
throw error
}
return response.json()
}