Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add KY data provider to simple-rest package #6544

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/simple-rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,30 @@
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./ky": {
"import": {
"types": "./dist/ky/index.d.mts",
"default": "./dist/ky.mjs"
},
"require": {
"types": "./dist/ky/index.d.cts",
"default": "./dist/ky.cjs"
}
}
},
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"typesVersions": {
"*": {
".": [
"dist/index.d.ts"
],
"ky": [
"dist/ky/index.d.ts"
]
}
},
"typings": "dist/index.d.ts",
"files": [
"dist",
Expand All @@ -48,9 +68,12 @@
"@refinedev/cli": "^2.16.33",
"@refinedev/core": "^4.52.0",
"@types/jest": "^29.2.4",
"axios": "^1.6.2",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"axios": "^1.6.2",

We don't need this, it should be in dependencies already.

"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"ky": "^1.7.2",
"nock": "^13.4.0",
"query-string": "^7.1.1",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use qs package because it supports encoding query params with nested structures.

"ts-jest": "^29.1.2",
"tslib": "^2.6.2",
"tsup": "^6.7.0",
Expand Down
8 changes: 8 additions & 0 deletions packages/simple-rest/src/ky/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { stringify } from "query-string";
import { dataProvider } from "./provider.js";

export default dataProvider;

export * from "../utils/index.js";

export { stringify };
274 changes: 274 additions & 0 deletions packages/simple-rest/src/ky/provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
import { stringify } from "query-string";
import type { KyInstance } from "ky";
import { kyInstance, createKyInstance } from "./utils/ky";
import { generateSort, generateFilter } from "../utils";
import type {
DataProvider,
GetListParams,
GetListResponse,
GetManyParams,
GetManyResponse,
BaseRecord,
Pagination,
CreateParams,
CreateResponse,
UpdateParams,
UpdateResponse,
GetOneParams,
GetOneResponse,
DeleteOneParams,
DeleteOneResponse,
CustomParams,
CustomResponse,
} from "@refinedev/core";

type MethodTypes = "get" | "delete" | "head" | "options";
type MethodTypesWithBody = "post" | "put" | "patch";
const handleRequest = async (
httpClient: KyInstance,
method: MethodTypes | MethodTypesWithBody,
url: string,
config?: { headers?: Record<string, string>; json?: unknown },
) => {
switch (method) {
case "get":
return httpClient.get(url, config);
case "post":
return httpClient.post(url, config);
case "put":
return httpClient.put(url, config);
case "patch":
return httpClient.patch(url, config);
case "delete":
return httpClient.delete(url, config);
case "head":
return httpClient.head(url, config);
default:
throw new Error(`Unsupported method: ${method}`);
}
};

export const dataProvider = (
apiUrl: string,
httpClient = kyInstance,
): Omit<
Required<DataProvider>,
"createMany" | "updateMany" | "deleteMany"
> => ({
getApiUrl: () => apiUrl,
getList: async <TData extends BaseRecord>({
resource,
pagination,
filters,
sorters,
meta = {},
}: GetListParams): Promise<GetListResponse<TData>> => {
const url = `${apiUrl}/${resource}`;

const {
current = 1,
pageSize = 10,
mode = "server",
} = pagination ?? ({} as Pagination);
const { headers: headersFromMeta, method } = meta ?? {};
const requestMethod = (method as MethodTypes) ?? "get";

const queryFilters = generateFilter(filters);

const query: {
_start?: number;
_end?: number;
_sort?: string;
_order?: string;
} = {};

if (mode === "server") {
query._start = (current - 1) * pageSize;
query._end = current * pageSize;
}

const generatedSort = generateSort(sorters);
if (generatedSort) {
const { _sort, _order } = generatedSort;
query._sort = _sort.join(",");
query._order = _order.join(",");
}

const combinedQuery = { ...query, ...queryFilters };
const urlWithQuery = Object.keys(combinedQuery).length
? `${url}?${stringify(combinedQuery)}`
: url;

const response = await handleRequest(
httpClient,
requestMethod,
urlWithQuery,
{
headers: headersFromMeta,
},
);

const data = (await response.json()) as TData[];
const total = +(response.headers.get("x-total-count") ?? 0) || data.length;

return { data, total };
},
getMany: async <TData extends BaseRecord>({
resource,
ids,
meta = {},
}: GetManyParams): Promise<GetManyResponse<TData>> => {
const { headers } = meta;
const requestMethod = meta.method ?? "get";

const response = await httpClient.get(
`${apiUrl}/${resource}?${stringify({ id: ids })}`,
{ headers },
);

const data = (await response.json()) as TData[];

return {
data,
};
},

create: async <TData extends BaseRecord, TVariables = {}>({
resource,
variables,
meta = {},
}: CreateParams<TVariables>): Promise<CreateResponse<TData>> => {
const url = `${apiUrl}/${resource}`;

const { headers, method } = meta;
const requestMethod = (method as MethodTypesWithBody) ?? "post";

const response = await httpClient[requestMethod](url, {
json: variables,
headers,
});

const data = (await response.json()) as TData;

return {
data,
};
},

update: async <TData extends BaseRecord, TVariables = {}>({
resource,
id,
variables,
meta = {},
}: UpdateParams<TVariables>): Promise<UpdateResponse<TData>> => {
const url = `${apiUrl}/${resource}/${id}`;

const { headers, method } = meta;
const requestMethod = (method as MethodTypesWithBody) ?? "patch";

const response = await httpClient[requestMethod](url, {
json: variables,
headers,
});

const data = (await response.json()) as TData;

return {
data,
};
},
getOne: async <TData extends BaseRecord>({
resource,
id,
meta = {},
}: GetOneParams): Promise<GetOneResponse<TData>> => {
const url = `${apiUrl}/${resource}/${id}`;

const { headers, method } = meta;
const requestMethod = (method as MethodTypes) ?? "get";

const response = await (httpClient as Record<string, any>)[requestMethod](
url,
{ headers },
);

const data = (await response.json()) as TData;

return {
data,
};
},
deleteOne: async <TData extends BaseRecord, TVariables = {}>({
resource,
id,
variables,
meta = {},
}: DeleteOneParams<TVariables>): Promise<DeleteOneResponse<TData>> => {
const url = `${apiUrl}/${resource}/${id}`;

const { headers, method } = meta;
const requestMethod = (method as MethodTypesWithBody) ?? "delete";

const response = await httpClient[requestMethod](url, {
json: variables,
headers,
});

const data = (await response.json()) as TData;

return {
data,
};
},

custom: async <
TData extends BaseRecord,
TQuery = unknown,
TPayload = unknown,
>({
url,
method,
filters,
sorters,
payload,
query,
headers,
}: CustomParams<TQuery, TPayload>): Promise<CustomResponse<TData>> => {
let requestUrl = `${url}?`;

if (sorters) {
const generatedSort = generateSort(sorters);
if (generatedSort) {
const { _sort, _order } = generatedSort;
const sortQuery = {
_sort: _sort.join(","),
_order: _order.join(","),
};
requestUrl = `${requestUrl}&${stringify(sortQuery)}`;
}
}

if (filters) {
const filterQuery = generateFilter(filters);
requestUrl = `${requestUrl}&${stringify(filterQuery)}`;
}

if (query) {
requestUrl = `${requestUrl}&${stringify(query)}`;
}

const response = await httpClient[method as MethodTypesWithBody](
requestUrl,
{
json: payload,
headers,
},
);

const data = await response.json();

return {
data: data as TData,
};
},
});
4 changes: 4 additions & 0 deletions packages/simple-rest/src/ky/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { mapOperator } from "../../utils/mapOperator";
export { generateSort } from "../../utils/generateSort";
export { generateFilter } from "../../utils/generateFilter";
export { kyInstance } from "./ky";
44 changes: 44 additions & 0 deletions packages/simple-rest/src/ky/utils/ky.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { HttpError } from "@refinedev/core";
import ky from "ky";
import type { KyInstance, Options as KyOptions } from "ky";

const handleErrorResponse = async (response: Response): Promise<void> => {
if (!response.ok) {
const customError: HttpError = {
message: response.statusText,
statusCode: response.status,
};

try {
customError.data = await response.clone().json();
} catch {
customError.data = await response.clone().text();
}

throw customError;
}
};

export const kyInstance = ky.create({
hooks: {
afterResponse: [
async (_request, _options, response) => handleErrorResponse(response),
],
},
});

export const createKyInstance = (
baseUrl?: string,
options?: KyOptions,
): KyInstance => {
return ky.create({
prefixUrl: baseUrl,
...options,
hooks: {
afterResponse: [
async (_request, _options, response) => handleErrorResponse(response),
],
...options?.hooks,
},
});
};
Comment on lines +22 to +44
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need both?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kyInstance is a default instance of ky with a pre-configured setup (e.g., error handling hooks). kyInstance is sufficient for refinedev usecase.

I added createKyInstance to allow more flexibility, like using multiple APIs or customizing hooks if needed. If this flexibility isn’t useful for refine.dev right now, we can remove it to keep things simpler.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where do we use createKyInstance?

Loading