Skip to content

Commit

Permalink
fix:types
Browse files Browse the repository at this point in the history
  • Loading branch information
prc5 committed Jul 6, 2024
1 parent c2bb5a4 commit a32b436
Show file tree
Hide file tree
Showing 17 changed files with 50 additions and 55 deletions.
4 changes: 2 additions & 2 deletions examples/next-app-router/app/ssr/client-component.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";

import React, { useState } from "react";
import { ExtractAdapterReturnType, RequestInstance } from "@hyper-fetch/core";
import { ExtractAdapterResolvedType, RequestInstance } from "@hyper-fetch/core";
import { UseFetchRequest, useFetch } from "@hyper-fetch/react";
import { Stack, Button } from "@mui/material";
import IconButton from "@mui/material/IconButton";
Expand All @@ -14,7 +14,7 @@ import { Request } from "../../components/request";
import { getUser } from "../../api";

export const ClientComponents: React.FC<{
fallback: Partial<ExtractAdapterReturnType<UseFetchRequest<RequestInstance>>>;
fallback: Partial<ExtractAdapterResolvedType<UseFetchRequest<RequestInstance>>>;
}> = (props) => {
const [dep, setDep] = useState(+new Date());
const [disabled, setDisabled] = useState(true);
Expand Down
9 changes: 5 additions & 4 deletions packages/core/src/cache/cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EventEmitter from "events";

import { AdapterInstance, ResponseType } from "adapter";
import { AdapterInstance, ExtractAdapterMethodType, ResponseType } from "adapter";
import { ClientInstance } from "client";
import { ResponseDetailsType, LoggerType } from "managers";
import {
Expand Down Expand Up @@ -81,7 +81,7 @@ export class Cache<C extends ClientInstance> {

// Once refresh error occurs we don't want to override already valid data in our cache with the thrown error
// We need to check it against cache and return last valid data we have
const processedResponse = typeof response === "function" ? response(cachedData) : response;
const processedResponse = typeof response === "function" ? response(cachedData || null) : response;
const data = getCacheData(cachedData, processedResponse);

const newCacheData: CacheValueType<any, any, ExtractAdapterType<Request>> = {
Expand All @@ -92,7 +92,7 @@ export class Cache<C extends ClientInstance> {
queueKey: request.queueKey,
effectKey: request.effectKey,
endpoint: request.endpoint,
method: request.method,
method: request.method as ExtractAdapterMethodType<ExtractAdapterType<Request>>,
garbageCollection,
};

Expand Down Expand Up @@ -140,7 +140,8 @@ export class Cache<C extends ClientInstance> {
ExtractAdapterType<Request>
>(cacheKey);

const processedResponse = typeof partialResponse === "function" ? partialResponse(cachedData) : partialResponse;
const processedResponse =
typeof partialResponse === "function" ? partialResponse(cachedData || null) : partialResponse;
if (cachedData) {
this.set(request, { ...cachedData, ...processedResponse });
}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/cache/cache.types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Cache } from "cache";
import { AdapterInstance, ResponseType } from "adapter";
import { AdapterInstance, ExtractAdapterMethodType, ResponseType } from "adapter";
import { ResponseDetailsType } from "managers";
import { ClientInstance } from "../client";
import { RequestInstance } from "request";
Expand Down Expand Up @@ -47,7 +47,7 @@ export type CacheValueType<
queueKey: string;
effectKey: string;
endpoint: string;
method: string;
method: ExtractAdapterMethodType<Adapter>;
garbageCollection: number;
};

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/cache/cache.utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { ResponseDetailsType } from "managers";
import { RequestInstance } from "request";
import { ExtractAdapterReturnType } from "types";
import { ExtractAdapterResolvedType } from "types";

export const getCacheData = <T extends RequestInstance>(
previousResponse: ExtractAdapterReturnType<T> | undefined,
response: ExtractAdapterReturnType<T> & ResponseDetailsType,
): ExtractAdapterReturnType<T> & ResponseDetailsType => {
previousResponse: ExtractAdapterResolvedType<T> | undefined,
response: ExtractAdapterResolvedType<T> & ResponseDetailsType,
): ExtractAdapterResolvedType<T> & ResponseDetailsType => {
const { data, success } = response;

const previousData = !success && previousResponse ? previousResponse.data : null;
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ import { ExtractAdapterType, NegativeTypes } from "types";
export class Client<
GlobalErrorType extends ClientErrorType = Error,
Adapter extends AdapterInstance = AdapterType,
EndpointMapper extends DefaultEndpointMapper = (
endpoint: ExtractAdapterEndpointType<Adapter>,
) => ExtractAdapterEndpointType<Adapter>,
EndpointMapper extends DefaultEndpointMapper = (endpoint: any) => any,
> {
readonly url: string;
public debug: boolean;
Expand Down Expand Up @@ -506,7 +504,7 @@ export class Client<
LocalError,
EndpointType extends string ? EndpointType : typeof endpoint,
Client<GlobalErrorType, ExtractedAdapterType, EndpointMapper>
>(this as any, mappedParams);
>(this as unknown as Client<GlobalErrorType, ExtractedAdapterType, EndpointMapper>, mappedParams);
};
};
}
2 changes: 1 addition & 1 deletion packages/core/src/client/client.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ export type StringifyCallbackType = (queryParams: QueryParamsType | string | Neg

// Mapper

export type DefaultEndpointMapper<EndpointType = any> = (endpoint: any) => EndpointType;
export type DefaultEndpointMapper<EndpointType = any> = (endpoint: EndpointType) => string;
3 changes: 2 additions & 1 deletion packages/core/src/managers/request/request.manager.events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from "managers";
import { AdapterInstance } from "adapter";
import { ExtendRequest, RequestInstance } from "request";
import { Client } from "client";

export const getRequestManagerEvents = (emitter: EventEmitter) => ({
/**
Expand Down Expand Up @@ -72,7 +73,7 @@ export const getRequestManagerEvents = (emitter: EventEmitter) => ({

// Response
emitResponse: <Adapter extends AdapterInstance>(
data: RequestResponseEventType<ExtendRequest<RequestInstance, { adapter: Adapter }>>,
data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter, any> }>>,
): void => {
emitter.emit(getResponseKey(), data);
emitter.emit(getResponseByIdKey(data.requestId), data);
Expand Down
19 changes: 9 additions & 10 deletions packages/core/src/request/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,11 @@ import {
} from "request";
import { ClientErrorType, ClientInstance } from "client";
import { getUniqueRequestId } from "utils";
import {
ExtractAdapterMethodType,
ExtractAdapterOptionsType,
QueryParamsType,
ResponseType,
ExtractAdapterEndpointType,
} from "adapter";
import { ExtractAdapterMethodType, ExtractAdapterOptionsType, QueryParamsType, ResponseType } from "adapter";
import {
ExtractClientAdapterType,
ExtractClientGlobalError,
ExtractEndpointType,
ExtractParamsType,
ExtractPayloadType,
ExtractQueryParamsType,
Expand Down Expand Up @@ -56,7 +51,7 @@ export class Request<
Payload,
QueryParams,
LocalError extends ClientErrorType, // Additional Error for specific endpoint
Endpoint extends ExtractAdapterEndpointType<ExtractClientAdapterType<Client>>,
Endpoint extends string,
Client extends ClientInstance,
HasData extends true | false = false,
HasParams extends true | false = false,
Expand Down Expand Up @@ -397,8 +392,12 @@ export class Request<

public toJSON(): RequestJSON<this> {
return {
requestOptions: this.requestOptions,
endpoint: this.endpoint,
requestOptions: this.requestOptions as RequestOptionsType<
ExtractEndpointType<this>,
ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
>,
endpoint: this.endpoint as ExtractEndpointType<this>,
headers: this.headers,
auth: this.auth,
method: this.method,
Expand Down
12 changes: 4 additions & 8 deletions packages/core/src/request/request.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ export type AdapterProgressType = {
*/
export type RequestJSON<Request extends RequestInstance> = {
requestOptions: RequestOptionsType<
ExtractAdapterEndpointType<ExtractAdapterType<Request>>,
ExtractEndpointType<Request>,
ExtractAdapterOptionsType<ExtractAdapterType<Request>>,
ExtractAdapterMethodType<ExtractAdapterType<Request>>
>;
endpoint: ExtractAdapterEndpointType<ExtractAdapterType<Request>>;
endpoint: ExtractEndpointType<Request>;
method: ExtractAdapterMethodType<ExtractAdapterType<Request>>;
headers?: HeadersInit;
auth: boolean;
Expand Down Expand Up @@ -170,7 +170,7 @@ export type RequestConfigurationType<
Payload,
Params,
QueryParams,
GenericEndpoint,
GenericEndpoint extends string,
AdapterOptions,
MethodsType = HttpMethodsType,
> = {
Expand Down Expand Up @@ -291,11 +291,7 @@ export type ExtendRequest<
TypeWithDefaults<Properties, "payload", ExtractPayloadType<Req>>,
TypeWithDefaults<Properties, "queryParams", ExtractQueryParamsType<Req>>,
TypeWithDefaults<Properties, "localError", ExtractLocalErrorType<Req>>,
Properties["endpoint"] extends ExtractAdapterEndpointType<ExtractAdapterType<Req>>
? Properties["endpoint"]
: ExtractEndpointType<Req> extends ExtractAdapterEndpointType<ExtractAdapterType<Req>>
? ExtractEndpointType<Req>
: never,
Properties["endpoint"] extends string ? Properties["endpoint"] : ExtractEndpointType<Req>,
Properties["client"] extends ClientInstance ? Properties["client"] : ExtractClientType<Req>,
Properties["hasData"] extends true ? true : ExtractHasDataType<Req>,
Properties["hasParams"] extends true ? true : ExtractHasParamsType<Req>,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/request/request.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export const sendRequest = <Request extends RequestInstance>(
const { details, response } = values;
isResolved = true;

const mapping = request.responseMapper?.(response);
const mapping = request.__responseMapper?.(response);

const isOfflineStatus = request.offline && details.isOffline;
const willRetry = canRetryRequest(details.retries, request.retry);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/types/fetch.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ResponseType } from "adapter";
import { ExtractRouteParams, Request, RequestInstance } from "request";
import { ExtractClientAdapterType, ExtractClientGlobalError } from "./client.types";

export type ExtractAdapterReturnType<T extends RequestInstance> = ResponseType<
export type ExtractAdapterResolvedType<T extends RequestInstance> = ResponseType<
ExtractResponseType<T>,
ExtractErrorType<T>,
ExtractAdapterType<T>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RequestInstance, ExtractAdapterReturnType } from "@hyper-fetch/core";
import { RequestInstance, ExtractAdapterResolvedType } from "@hyper-fetch/core";
import { act, waitFor } from "@testing-library/react";
import { createHttpMockingServer } from "@hyper-fetch/testing";

Expand Down Expand Up @@ -85,7 +85,7 @@ describe("useSubmit [ Bounce ]", () => {
mockRequest(request);
const response = renderUseSubmit(request, hookDebounceOptions);

let value: ExtractAdapterReturnType<RequestInstance>[] = [];
let value: ExtractAdapterResolvedType<RequestInstance>[] = [];
await act(async () => {
const promiseOne = await response.result.current.submit();
await waitForRender(1);
Expand All @@ -99,7 +99,7 @@ describe("useSubmit [ Bounce ]", () => {
});

expect(value).toHaveLength(4);
const isResponse = (res: ExtractAdapterReturnType<RequestInstance>) => {
const isResponse = (res: ExtractAdapterResolvedType<RequestInstance>) => {
return !!res.data && !res.error && res.status === 200 && res.extra;
};
expect(value).toSatisfyAny(isResponse);
Expand Down Expand Up @@ -229,7 +229,7 @@ describe("useSubmit [ Bounce ]", () => {
mockRequest(request);
const response = renderUseSubmit(request, hookThrottleOptions);

let value: ExtractAdapterReturnType<RequestInstance>[] = [];
let value: ExtractAdapterResolvedType<RequestInstance>[] = [];
await act(async () => {
const promiseOne = await response.result.current.submit();
await waitForRender(1);
Expand All @@ -243,7 +243,7 @@ describe("useSubmit [ Bounce ]", () => {
});

expect(value).toHaveLength(4);
const isResponse = (res: ExtractAdapterReturnType<RequestInstance>) => {
const isResponse = (res: ExtractAdapterResolvedType<RequestInstance>) => {
return !!res.data && !res.error && res.status === 200 && !!res.extra;
};
expect(value).toSatisfyAny(isResponse);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
ExtractAdapterType,
ExtractAdapterStatusType,
ExtractAdapterExtraType,
ExtractAdapterReturnType,
ExtractAdapterResolvedType,
NullableType,
} from "@hyper-fetch/core";

Expand All @@ -17,7 +17,7 @@ import { isEqual } from "utils";
export type UseTrackedStateProps<T extends RequestInstance> = {
request: T;
logger: LoggerType;
initialData: NullableType<Partial<ExtractAdapterReturnType<T>>>;
initialData: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
dispatcher: Dispatcher;
dependencyTracking: boolean;
defaultCacheEmitting?: boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
RequestInstance,
ExtractResponseType,
ExtractErrorType,
ExtractAdapterReturnType,
ExtractAdapterResolvedType,
Dispatcher,
ExtractAdapterType,
ExtractAdapterExtraType,
Expand Down Expand Up @@ -33,7 +33,7 @@ export const isStaleCacheData = (cacheTime: number, cacheTimestamp: NullableType

export const getValidCacheData = <T extends RequestInstance>(
request: T,
initialData: NullableType<Partial<ExtractAdapterReturnType<T>>>,
initialData: NullableType<Partial<ExtractAdapterResolvedType<T>>>,
cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>>,
): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>> | null => {
const isStale = isStaleCacheData(request.cacheTime, cacheData?.timestamp);
Expand All @@ -49,7 +49,7 @@ export const getValidCacheData = <T extends RequestInstance>(
status: null,
success: true,
extra: null,
...((initialData || {}) as Partial<ExtractAdapterReturnType<T>>),
...((initialData || {}) as Partial<ExtractAdapterResolvedType<T>>),
...getDetailsState(),
cacheTime: 1000,
clearKey: request.client.cache.clearKey,
Expand All @@ -70,7 +70,7 @@ export const getTimestamp = (timestamp?: NullableType<number | Date>) => {
};

export const getInitialState = <T extends RequestInstance>(
initialData: NullableType<Partial<ExtractAdapterReturnType<T>>>,
initialData: NullableType<Partial<ExtractAdapterResolvedType<T>>>,
dispatcher: Dispatcher,
request: T,
): UseTrackedStateType<T> => {
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/hooks/use-fetch/use-fetch.types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
RequestInstance,
NullableType,
ExtractAdapterReturnType,
ExtractAdapterResolvedType,
ExtendRequest,
ExtractPayloadType,
ExtractParamsType,
Expand Down Expand Up @@ -40,7 +40,7 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
/**
* If cache is empty we can use placeholder data.
*/
initialData?: NullableType<Partial<ExtractAdapterReturnType<T>>>;
initialData?: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
/**
* Enable/disable refresh data
*/
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/hooks/use-submit/use-submit.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useMemo, useRef } from "react";
import {
Request,
getRequestKey,
ExtractAdapterReturnType,
ExtractAdapterResolvedType,
RequestInstance,
sendRequest,
ResponseType,
Expand Down Expand Up @@ -126,7 +126,7 @@ export const useSubmit = <RequestType extends RequestInstance>(
});
};

return new Promise<ExtractAdapterReturnType<RequestType>>((resolve) => {
return new Promise<ExtractAdapterResolvedType<RequestType>>((resolve) => {
const performSubmit = async () => {
logger.debug(`Submitting request`, { disabled, submitOptions });
if (bounce) {
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/hooks/use-submit/use-submit.types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ExtractAdapterReturnType, NullableType, RequestInstance, RequestSendType } from "@hyper-fetch/core";
import { ExtractAdapterResolvedType, NullableType, RequestInstance, RequestSendType } from "@hyper-fetch/core";

import { isEqual } from "utils";
import {
Expand All @@ -20,7 +20,7 @@ export type UseSubmitOptionsType<T extends RequestInstance> = {
/**
* If cache is empty we can use placeholder data.
*/
initialData?: NullableType<Partial<ExtractAdapterReturnType<T>>>;
initialData?: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
/**
* Enable/disable debouncing for often changing keys or refreshing, to limit requests to server.
*/
Expand Down

0 comments on commit a32b436

Please sign in to comment.