Skip to content

Commit

Permalink
fix: 🏷️ add types to $csrfFetch
Browse files Browse the repository at this point in the history
Resolves #19
  • Loading branch information
Morgbn committed Feb 21, 2024
1 parent cd419b8 commit b3ffc49
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { $fetch } from 'ofetch'
import type { FetchOptions } from 'ofetch'
import type { FetchOptions, FetchRequest, $Fetch } from 'ofetch'
import { defineNuxtPlugin, useCsrf } from '#imports'

// types copied from ofetch (not exposed by oftech)
interface ResponseMap {
blob: Blob;
text: string;
arrayBuffer: ArrayBuffer;
stream: ReadableStream<Uint8Array>;
}
type ResponseType = keyof ResponseMap | "json";
type MappedType<R extends ResponseType, JsonType = any> = R extends keyof ResponseMap ? ResponseMap[R] : JsonType;

export default defineNuxtPlugin(() => {
const { csrf } = useCsrf()
return {
provide: {
csrfFetch: (request: string, options?: FetchOptions, fetch = $fetch) => {
csrfFetch: <T = any, R extends ResponseType = "json"> (request: FetchRequest, options?: FetchOptions<R>, fetch: $Fetch = $fetch): Promise<MappedType<R, T>> => {
if (!options) { options = {} }
options.headers = (options.headers || {}) as Record<string, string>
options.headers['csrf-token'] = csrf
Expand Down

0 comments on commit b3ffc49

Please sign in to comment.