Skip to content

Commit

Permalink
feat(http): allow passing Accept-Language header (#454)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Jan 29, 2024
1 parent deea3af commit ce9b1e3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 6 additions & 0 deletions docs/network-requests/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ interface HttpOptions {
* @default ofetch
*/
client?: HttpClient
/**
* The language to use for Accept-Language header.
*
* @default undefined
*/
lang?: 'en' | 'ja'
}

interface HttpClient {
Expand Down
9 changes: 8 additions & 1 deletion lib/http/Http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { parse as parseCookie } from '@tinyhttp/cookie'
import FileSaver from 'file-saver'
import { type FetchOptions, type FetchRequest, type FetchResponse, ofetch } from 'ofetch'
import { stringify } from 'qs'
import { type Lang } from '../composables/Lang'

export interface HttpClient {
<T = any>(request: FetchRequest, options?: Omit<FetchOptions, 'method'>): Promise<T>
Expand All @@ -13,12 +14,14 @@ export interface HttpOptions {
baseUrl?: string
xsrfUrl?: string | false
client?: HttpClient
lang?: Lang
}

export class Http {
private static baseUrl: string | undefined = undefined
private static xsrfUrl: string | false = '/api/csrf-cookie'
private static client: HttpClient = ofetch
private static lang: Lang | undefined = undefined

static config(options: HttpOptions) {
if (options.baseUrl) {
Expand All @@ -30,6 +33,9 @@ export class Http {
if (options.client) {
Http.client = options.client
}
if (options.lang) {
Http.lang = options.lang
}
}

private async ensureXsrfToken(): Promise<string | undefined> {
Expand Down Expand Up @@ -70,7 +76,8 @@ export class Http {
...options,
headers: {
Accept: 'application/json',
...(xsrfToken && { 'X-XSRF-TOKEN': xsrfToken }),
...(xsrfToken && { 'X-Xsrf-Token': xsrfToken }),
...(Http.lang && { 'Accept-Language': Http.lang }),
...options.headers
}
}
Expand Down

0 comments on commit ce9b1e3

Please sign in to comment.