Skip to content

Commit

Permalink
feat(hooks): useTable supports passing in the default transformer clo…
Browse files Browse the repository at this point in the history
…se#595
  • Loading branch information
Azir-11 committed Aug 13, 2024
1 parent 5094f0e commit be66841
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 21 deletions.
44 changes: 23 additions & 21 deletions src/hooks/common/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,33 @@ export function useTable<A extends NaiveUI.TableApiFn>(config: NaiveUI.NaiveTabl

const isMobile = computed(() => appStore.isMobile);

const { apiFn, apiParams, immediate, showTotal } = config;
const { apiFn, transformer, apiParams, immediate, showTotal } = config;

const SELECTION_KEY = '__selection__';

const EXPAND_KEY = '__expand__';

const defaultTransformer = (res: Awaited<ReturnType<A>>) => {
const { records = [], current = 1, size = 10, total = 0 } = res.data || {};

// Ensure that the size is greater than 0, If it is less than 0, it will cause paging calculation errors.
const pageSize = size <= 0 ? 10 : size;

const recordsWithIndex = records.map((item, index) => {
return {
...item,
index: (current - 1) * pageSize + index + 1
};
});

return {
data: recordsWithIndex,
pageNum: current,
pageSize,
total
};
};

const {
loading,
empty,
Expand All @@ -37,26 +58,7 @@ export function useTable<A extends NaiveUI.TableApiFn>(config: NaiveUI.NaiveTabl
apiFn,
apiParams,
columns: config.columns,
transformer: res => {
const { records = [], current = 1, size = 10, total = 0 } = res.data || {};

// Ensure that the size is greater than 0, If it is less than 0, it will cause paging calculation errors.
const pageSize = size <= 0 ? 10 : size;

const recordsWithIndex = records.map((item, index) => {
return {
...item,
index: (current - 1) * pageSize + index + 1
};
});

return {
data: recordsWithIndex,
pageNum: current,
pageSize,
total
};
},
transformer: transformer || defaultTransformer,
getColumnChecks: cols => {
const checks: NaiveUI.TableColumnCheck[] = [];

Expand Down
7 changes: 7 additions & 0 deletions src/typings/naive-ui.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,12 @@ declare namespace NaiveUI {
* @default false
*/
showTotal?: boolean;
/**
* the custom transformer function
*
* @param res the response data
* @returns the transformed data
*/
transformer?: (res: Awaited<ReturnType<A>>) => { data: any[]; pageNum: number; pageSize: number; total: number };
};
}

0 comments on commit be66841

Please sign in to comment.