Skip to content

Commit

Permalink
feat(http): allow specifying base url (#433)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd authored Jan 9, 2024
1 parent 4af35d0 commit d322fa5
Showing 1 changed file with 29 additions and 27 deletions.
56 changes: 29 additions & 27 deletions lib/http/Http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { $fetch, type FetchOptions } from 'ofetch'
import { stringify } from 'qs'

export class Http {
static base: string | undefined = undefined
static xsrfUrl = '/api/csrf-cookie'

private async ensureXsrfToken(): Promise<string | undefined> {
Expand Down Expand Up @@ -35,6 +36,7 @@ export class Http {
return [
`${url}${queryString ? `?${queryString}` : ''}`,
{
baseURL: Http.base,
method,
credentials: 'include',
...options,
Expand All @@ -55,33 +57,6 @@ export class Http {
return $fetch.raw<T, any>(...(await this.buildRequest(url, options)))
}

private objectToFormData(obj: any, form?: FormData, namespace?: string) {
const fd = form || new FormData()
let formKey: string

for (const property in obj) {
if (Reflect.has(obj, property)) {
if (namespace) {
formKey = `${namespace}[${property}]`
} else {
formKey = property
}

if (obj[property] === undefined) {
continue
}

if (typeof obj[property] === 'object' && !(obj[property] instanceof Blob)) {
this.objectToFormData(obj[property], fd, property)
} else {
fd.append(formKey, obj[property])
}
}
}

return fd
}

async get<T = any>(url: string, options?: FetchOptions): Promise<T> {
return this.performRequest<T>(url, { method: 'GET', ...options })
}
Expand Down Expand Up @@ -132,6 +107,33 @@ export class Http {

FileSaver.saveAs(blob, filename as string)
}

private objectToFormData(obj: any, form?: FormData, namespace?: string) {
const fd = form || new FormData()
let formKey: string

for (const property in obj) {
if (Reflect.has(obj, property)) {
if (namespace) {
formKey = `${namespace}[${property}]`
} else {
formKey = property
}

if (obj[property] === undefined) {
continue
}

if (typeof obj[property] === 'object' && !(obj[property] instanceof Blob)) {
this.objectToFormData(obj[property], fd, property)
} else {
fd.append(formKey, obj[property])
}
}
}

return fd
}
}

export type { FetchOptions }

0 comments on commit d322fa5

Please sign in to comment.