-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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", | ||
|
@@ -48,9 +68,12 @@ | |
"@refinedev/cli": "^2.16.33", | ||
"@refinedev/core": "^4.52.0", | ||
"@types/jest": "^29.2.4", | ||
"axios": "^1.6.2", | ||
"jest": "^29.3.1", | ||
"jest-environment-jsdom": "^29.3.1", | ||
"ky": "^1.7.2", | ||
"nock": "^13.4.0", | ||
"query-string": "^7.1.1", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's use |
||
"ts-jest": "^29.1.2", | ||
"tslib": "^2.6.2", | ||
"tsup": "^6.7.0", | ||
|
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 }; |
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, | ||
}; | ||
}, | ||
}); |
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"; |
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we need both? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
I added There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Where do we use |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't need this, it should be in dependencies already.