Skip to content

Commit

Permalink
refactor: move to types
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Oct 26, 2023
1 parent a9d2aef commit fc48d03
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 17 deletions.
11 changes: 8 additions & 3 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import type { Readable } from "node:stream";
import destr from "destr";
import { withBase, withQuery } from "ufo";
import type { Fetch, RequestInfo, RequestInit, Response } from "./types";
import type {
Fetch,
RequestInfo,
RequestInit,
Response,
ResponseType,
MappedType,
} from "./types";
import { createFetchError } from "./error";
import {
isPayloadMethod,
isJSONSerializable,
detectResponseType,
ResponseType,
MappedType,
mergeFetchOptions,
} from "./utils";

Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { createFetch } from "./base";

export * from "./base";
export type { ResponseType, ResponseMap, MappedType } from "./utils";

export type { ResponseType, ResponseMap, MappedType } from "./types";

// ref: https://github.com/tc39/proposal-global
const _globalThis = (function () {
Expand Down
14 changes: 14 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,17 @@ export type Fetch = typeof globalThis.fetch;
export type RequestInfo = globalThis.RequestInfo;
export type RequestInit = globalThis.RequestInit;
export type Response = globalThis.Response;

export interface ResponseMap {
blob: Blob;
text: string;
arrayBuffer: ArrayBuffer;
stream: ReadableStream<Uint8Array>;
}

export type ResponseType = keyof ResponseMap | "json";

export type MappedType<
R extends ResponseType,
JsonType = any,
> = R extends keyof ResponseMap ? ResponseMap[R] : JsonType;
14 changes: 1 addition & 13 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { FetchOptions } from "./fetch";
import type { ResponseType } from "./types";

const payloadMethods = new Set(
Object.freeze(["PATCH", "POST", "PUT", "DELETE"])
Expand Down Expand Up @@ -39,19 +40,6 @@ const textTypes = new Set([

const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;

export interface ResponseMap {
blob: Blob;
text: string;
arrayBuffer: ArrayBuffer;
stream: ReadableStream<Uint8Array>;
}

export type ResponseType = keyof ResponseMap | "json";
export type MappedType<
R extends ResponseType,
JsonType = any,
> = R extends keyof ResponseMap ? ResponseMap[R] : JsonType;

// This provides reasonable defaults for the correct parser based on Content-Type header.
export function detectResponseType(_contentType = ""): ResponseType {
if (!_contentType) {
Expand Down

0 comments on commit fc48d03

Please sign in to comment.