Skip to content

Commit 0ec5587

Browse files
committed
Add useInfinite and switch to ESM
1 parent 9a19679 commit 0ec5587

File tree

9 files changed

+70
-62
lines changed

9 files changed

+70
-62
lines changed

jest.config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
module.exports = {
1+
export default {
22
preset: "ts-jest",
33
transform: {
44
"^.+\\.[tj]sx?$": "babel-jest",

package.json

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"url": "git+https://github.com/BlueManCZ/swr-models.git"
1818
},
1919
"license": "MIT",
20+
"type": "module",
2021
"main": "dist/index.js",
2122
"types": "dist/index.d.ts",
2223
"scripts": {
@@ -26,18 +27,23 @@
2627
"prepublishOnly": "npm run build"
2728
},
2829
"peerDependencies": {
29-
"react": "^16.11 || ^17 || ^18 || ^19",
30-
"@types/react": "^19.2.7",
31-
"swr": "^2.3.7"
30+
"react": ">=16.11.0",
31+
"swr": "^2.0.0"
32+
},
33+
"peerDependenciesMeta": {
34+
"@types/react": {
35+
"optional": true
36+
}
3237
},
3338
"devDependencies": {
3439
"@babel/preset-env": "^7.28.5",
3540
"@babel/preset-typescript": "^7.28.5",
3641
"@biomejs/biome": "^2.3.8",
3742
"@types/jest": "^30.0.0",
43+
"@types/react": "^19.2.7",
3844
"jest": "^30.2.0",
3945
"jest-environment-jsdom": "^30.2.0",
40-
"react": "^16.11 || ^17 || ^18 || ^19",
46+
"react": "^19.2.3",
4147
"swr": "^2.3.7",
4248
"ts-jest": "^29.4.6",
4349
"ts-node": "^10.9.2",

pnpm-lock.yaml

Lines changed: 14 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/SWRModelEndpoint.ts

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
1-
import type { MutatorCallback } from "swr";
1+
import useSWR, { type MutatorCallback, mutate } from "swr";
22
import type { MutatorOptions } from "swr/_internal";
3-
4-
import { customMutate, customSWR } from "./SWRUtils";
3+
import useSWRInfinite from "swr/infinite";
54
import type { Fetcher, SWRModelEndpointConfig, SWRModelEndpointConfigOverride } from "./types";
6-
import { convertObjectValuesToString, jsonFetcher } from "./utils";
5+
import { convertObjectValuesToString, getJson, jsonFetcher } from "./utils";
76

87
export class SWRModelEndpoint<T> {
9-
private readonly config: SWRModelEndpointConfig;
8+
private readonly config: SWRModelEndpointConfig<T>;
109

11-
constructor(config: SWRModelEndpointConfig) {
10+
constructor(config: SWRModelEndpointConfig<T>) {
1211
this.config = config;
1312
}
1413

15-
private _configMerge(config?: SWRModelEndpointConfigOverride) {
14+
private _configMerge(config?: SWRModelEndpointConfigOverride<T>) {
1615
return {
1716
...this.config,
1817
...config,
1918
};
2019
}
2120

22-
public endpoint(config?: SWRModelEndpointConfigOverride): string | null {
21+
public endpoint(config?: SWRModelEndpointConfigOverride<T>): string | null {
2322
if (Array.isArray(config?.id)) {
2423
throw new Error("id can be array only in ssr fallback.");
2524
}
@@ -45,15 +44,15 @@ export class SWRModelEndpoint<T> {
4544
return c?.trailingSlash && !r.endsWith("/") ? `${r}/${p ? `?${p}` : ""}` : `${r}${p ? `?${p}` : ""}`;
4645
}
4746

48-
public fetch<R = T>(fetcher: Fetcher, config?: SWRModelEndpointConfigOverride) {
47+
public fetch<R = T>(fetcher: Fetcher, config?: SWRModelEndpointConfigOverride<T>) {
4948
const endpoint = this.endpoint(config);
5049
if (endpoint === null) {
5150
return Promise.resolve(null);
5251
}
5352
return fetcher<R>(endpoint);
5453
}
5554

56-
public async fetchFallback<R = T>(fetcher: Fetcher, config?: SWRModelEndpointConfigOverride) {
55+
public async fetchFallback<R = T>(fetcher: Fetcher, config?: SWRModelEndpointConfigOverride<T>) {
5756
const c = this._configMerge(config);
5857
const fallbackPairs: { [url: string]: R } = {};
5958
for (const id of Array.isArray(c?.id) ? c.id : [c?.id]) {
@@ -68,18 +67,18 @@ export class SWRModelEndpoint<T> {
6867
return fallbackPairs;
6968
}
7069

71-
public mutate<Data = unknown, T = Data>(
72-
config?: SWRModelEndpointConfigOverride,
73-
data?: T | Promise<T> | MutatorCallback<T>,
74-
opts?: boolean | MutatorOptions<Data, T>,
70+
public mutate<Data = unknown, R = Data>(
71+
config?: SWRModelEndpointConfigOverride<T>,
72+
data?: R | Promise<R> | MutatorCallback<R>,
73+
opts?: boolean | MutatorOptions<Data, R>,
7574
) {
76-
return customMutate(this.endpoint(config), data, opts);
75+
return mutate(this.endpoint(config), data, opts);
7776
}
7877

79-
public async update<T extends object | object[]>(
80-
data: T | Promise<T> | MutatorCallback<T>,
78+
public async update<R extends object | object[]>(
79+
data: R | Promise<R> | MutatorCallback<R>,
8180
onSuccess?: (response: Response) => void,
82-
config?: SWRModelEndpointConfigOverride,
81+
config?: SWRModelEndpointConfigOverride<T>,
8382
) {
8483
const c = this._configMerge(config);
8584
return this.mutate(c, data, {
@@ -100,7 +99,19 @@ export class SWRModelEndpoint<T> {
10099
});
101100
}
102101

103-
public use<R = T>(config?: SWRModelEndpointConfigOverride) {
104-
return customSWR<R>(this.endpoint(config), this._configMerge(config).swrConfig);
102+
public use<R = T>(config?: SWRModelEndpointConfigOverride<T>) {
103+
return useSWR<R>(this.endpoint(config), getJson, this._configMerge(config).swrConfig);
104+
}
105+
106+
public useInfinite(config?: SWRModelEndpointConfigOverride<T>) {
107+
const c = this._configMerge(config);
108+
return useSWRInfinite<T>((index, previousPageData) => {
109+
if (previousPageData && !c.pagination?.hasMore(previousPageData)) return null;
110+
const params = {
111+
...c.params,
112+
...(c.pagination ? c.pagination.getParams(index, previousPageData) : {}),
113+
};
114+
return this.endpoint({ ...c, params });
115+
});
105116
}
106117
}

src/SWRUtils.ts

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,11 @@
11
"use client";
22

33
import { useEffect, useState } from "react";
4-
import useSWR, { type Key, mutate, SWRConfig, type SWRConfiguration } from "swr";
54

65
import type { SWRModelEndpoint } from "./SWRModelEndpoint";
76
import type { SWRModelEndpointConfigOverride } from "./types";
8-
import { getJson } from "./utils";
97

10-
export function customSWR<T>(endpoint: Key, config?: SWRConfiguration) {
11-
// eslint-disable-next-line react-hooks/rules-of-hooks
12-
return useSWR<T>(endpoint, getJson, config);
13-
}
14-
15-
export const customMutate = mutate;
16-
export const CustomSWRConfig = SWRConfig;
17-
18-
export function useModel<T>(modelInstance: SWRModelEndpoint<T>, config?: SWRModelEndpointConfigOverride) {
8+
export function useModel<T>(modelInstance: SWRModelEndpoint<T>, config?: SWRModelEndpointConfigOverride<T>) {
199
const { data: original } = modelInstance.use(config);
2010
const [model, set] = useState(original);
2111
const [refreshLock, setRefreshLock] = useState(false);

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
export { SWRModelEndpoint } from "./SWRModelEndpoint";
2-
export { CustomSWRConfig, customMutate, useModel } from "./SWRUtils";
2+
export { useModel } from "./SWRUtils";
33
export { SWRModelEndpointConfigOverride } from "./types";
44
export { jsonFetcherFactory } from "./utils";

src/types.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,21 @@ import type { SWRConfiguration } from "swr";
22

33
export type Fetcher = <T>(url: string) => Promise<T>;
44

5-
export type SWRModelEndpointConfig = {
5+
export type SWRModelEndpointConfig<T> = {
66
key: string;
77
id?: number | string | number[] | string[] | null;
88
nonNullId?: boolean;
99
params?: Record<string, string | number | boolean | null>;
1010
nonNullParams?: boolean;
1111
trailingSlash?: boolean;
1212
swrConfig?: SWRConfiguration;
13+
pagination?: {
14+
hasMore: (previousData: T) => boolean;
15+
getParams: (
16+
index: number,
17+
previousData: T | null,
18+
) => Record<string, string | number | boolean | null>;
19+
};
1320
};
1421

15-
export type SWRModelEndpointConfigOverride = Omit<SWRModelEndpointConfig, "key">;
22+
export type SWRModelEndpointConfigOverride<T> = Omit<SWRModelEndpointConfig<T>, "key">;

src/utils.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,7 @@ export const getJson = (key: string) => jsonFetcher(key).then((response) => resp
1717

1818
/** Factory function for creating a JSON fetcher. This can be used to create a fetcher with a specific protocol, host and port. */
1919
export const jsonFetcherFactory =
20-
(
21-
protocol: string,
22-
host: string,
23-
port: string,
24-
cache: "force-cache" | "no-cache" = "no-cache",
25-
revalidate = 0,
26-
) =>
20+
(protocol: string, host: string, port: string, cache?: RequestCache, revalidate?: number) =>
2721
async <T>(endpoint: string): Promise<T> => {
2822
const url = `${protocol}://${host}:${port}/${endpoint}`;
2923
const response = await fetch(url, {

tsconfig.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{
22
"compilerOptions": {
33
"target": "es2019",
4-
"module": "commonjs",
4+
"module": "esnext",
5+
"moduleResolution": "bundler",
56
"esModuleInterop": true,
67
"forceConsistentCasingInFileNames": true,
78
"strict": true,

0 commit comments

Comments
 (0)