数据来源

数据来源 是一个围绕数据采集的简单包装。 这是一种"端口"在 清洁建筑。它允许您根据您的使用大小写来为数据采集工作做包装. 数据来源 用途 反应-平滑 在引擎盖下.
安装
npm install @gravity-ui/data-source @tanstack/react-query
@tanstack/react-query 是同级依赖.
快速启动
1. 设置数据管理器
第一,创建并提供 DataManager 在申请中:
import React from 'react';
import {ClientDataManager, DataManagerContext} from '@gravity-ui/data-source';
const dataManager = new ClientDataManager({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 minutes
retry: 3,
},
// ... other react-query options
},
});
function App() {
return (
<DataManagerContext.Provider value={dataManager}>
<YourApplication />
</DataManagerContext.Provider>
);
}
2. 定义错误类型和打包器
定义出错类型,并根据默认构造器为数据源制作构建器 :
import {makePlainQueryDataSource as makePlainQueryDataSourceBase} from '@gravity-ui/data-source';
export interface ApiError {
code: number;
title: string;
description?: string;
}
export const makePlainQueryDataSource = <TParams, TRequest, TResponse, TData, TError = ApiError>(
config: Omit<PlainQueryDataSource<TParams, TRequest, TResponse, TData, TError>, 'type'>,
): PlainQueryDataSource<TParams, TRequest, TResponse, TData, TError> => {
return makePlainQueryDataSourceBase(config);
};
3. 创建自定义数据记录组件
写一个 DataLoader 基于默认定义您显示装入状态和错误的组件 :
import {
DataLoader as DataLoaderBase,
DataLoaderProps as DataLoaderPropsBase,
ErrorViewProps,
} from '@gravity-ui/data-source';
export interface DataLoaderProps
extends Omit<DataLoaderPropsBase<ApiError>, 'LoadingView' | 'ErrorView'> {
LoadingView?: ComponentType;
ErrorView?: ComponentType<ErrorViewProps<ApiError>>;
}
export const DataLoader: React.FC<DataLoaderProps> = ({
LoadingView = YourLoader, // You can use your own loader component
ErrorView = YourError, // You can use your own error component
...restProps
}) => {
return <DataLoaderBase LoadingView={LoadingView} ErrorView={ErrorView} {...restProps} />;
};
4. 定义您的第一个数据来源
import {skipContext} from '@gravity-ui/data-source';
// Your API function
import {fetchUser} from './api';
export const userDataSource = makePlainQueryDataSource({
// Keys have to be unique. Maybe you should create a helper for making names of data sources
name: 'user',
// skipContext is a helper to skip 2 first parameters in the function (context and fetchContext)
fetch: skipContext(fetchUser),
// Optional: generate tags for advanced cache invalidation
tags: (params) => [`user:${params.userId}`, 'users'],
});
5. 组件的使用
import {useQueryData} from '@gravity-ui/data-source';
export const UserProfile: React.FC<{userId: number}> = ({userId}) => {
const {data, status, error, refetch} = useQueryData(userDataSource, {userId});
return (
<DataLoader status={status} error={error} errorAction={refetch}>
{data && <UserCard user={data} />}
</DataLoader>
);
};
核心概念
数据源类型
该图书馆提供两种主要的数据来源:
普通查询数据源
对于简单的请求/响应模式:
const userDataSource = makePlainQueryDataSource({
name: 'user',
fetch: skipContext(async (params: {userId: number}) => {
const response = await fetch(`/api/users/${params.userId}`);
return response.json();
}),
});
无限查询数据源
对于平面和无限卷轴:
const postsDataSource = makeInfiniteQueryDataSource({
name: 'posts',
fetch: skipContext(async (params: {page: number; limit: number}) => {
const response = await fetch(`/api/posts?page=${params.page}&limit=${params.limit}`);
return response.json();
}),
next: (lastPage, allPages) => {
if (lastPage.hasNext) {
return {page: allPages.length + 1, limit: 20};
}
return undefined;
},
});
状况管理
库将查询状态正常化为三个简单状态:
loading- 实际数据加载。 一样isLoading在反应查询中success- 可用数据(可用闲置跳过)error- 获取数据失败
空闲概念
图书馆提供特别服务 idle 用于跳过查询执行的符号 :
import {idle} from '@gravity-ui/data-source';
const UserProfile: React.FC<{userId?: number}> = ({userId}) => {
// Query won't execute if userId is not defined
const {data, status} = useQueryData(userDataSource, userId ? {userId} : idle);
return (
<DataLoader status={status} error={null}>
{data && <UserCard user={data} />}
</DataLoader>
);
};
当参数相等时 idle数字 :
- 查询不执行
- 现状
success - 数据尚存
undefined - 组件无需加载即可安全渲染
效益 idle数字 :
- 类型安全 - TypeScript正确推断有条件参数的类型
- 业绩 - 避免不必要的服务器请求
- 逻辑简化 - 不需要管理额外的
enabled状态 - 一致性 - 所有有条件查询的统一办法
这对有条件的查询特别有用,因为要在特定条件下装入数据,同时保持类型安全.
API 参考
创建数据源
makePlainQueryDataSource(config)
为简单的请求/响应模式创建纯查询数据源.
const dataSource = makePlainQueryDataSource({
name: 'unique-name',
fetch: skipContext(fetchFunction),
transformParams: (params) => transformedRequest,
transformResponse: (response) => transformedData,
tags: (params) => ['tag1', 'tag2'],
options: {
staleTime: 60000,
retry: 3,
// ... other react-query options
},
});
参数:
name- 数据来源的独特标识符fetch- 执行实际数据采集的函数transformParams(可选) - 在请求前转换输入参数transformResponse(可选) - 变换响应数据tags(可选) - 生成无效的缓存标记options(可选) - 重复查询选项
makeInfiniteQueryDataSource(config)
创建无限查询数据源,用于页码和无限滚动模式.
const infiniteDataSource = makeInfiniteQueryDataSource({
name: 'infinite-data',
fetch: skipContext(fetchFunction),
next: (lastPage, allPages) => nextPageParam || undefined,
prev: (firstPage, allPages) => prevPageParam || undefined,
// ... other options same as plain
});
补充参数:
next- 确定下一页参数的函数prev(可选) - 确定上一个页面参数的函数
反应钩
useQueryData(dataSource, params, options?)
用数据源获取数据的主钩.
const {data, status, error, refetch, ...rest} = useQueryData(
userDataSource,
{userId: 123},
{
enabled: true,
refetchInterval: 30000,
},
);
回返情况:
data- 获取的数据status- 当前状态(“ 装入” QQ“ 成功” QQ“ 错误” )error- 如果请求失败,则错误对象refetch- 手动调试数据的功能- 其他反应查询属性
useQueryResponses(responses)
将多个查询回复合并为一个状态.
const user = useQueryData(userDataSource, {userId});
const posts = useQueryData(postsDataSource, {userId});
const {status, error, refetch, refetchErrored} = useQueryResponses([user, posts]);
回返情况:
status- 所有查询的综合情况error- 第一次遇到错误refetch- 调试所有查询的功能refetchErrored- 仅调试失败查询的函数
useRefetchAll(states)
创建回调以调试多个查询.
const refetchAll = useRefetchAll([user, posts, comments]);
// refetchAll() will trigger refetch for all queries
useRefetchErrored(states)
创建回调只检查失败的查询 .
const refetchErrored = useRefetchErrored([user, posts, comments]);
// refetchErrored() will only refetch queries with errors
useDataManager()
从上下文返回数据管理器.
const dataManager = useDataManager();
await dataManager.invalidateTag('users');
useQueryContext()
返回查询上下文(用于在反应-query上建立自定义数据钩子基础).
反应组件
<DataLoader />
处理加载状态和错误的组件 .
<DataLoader
status={status}
error={error}
errorAction={refetch}
LoadingView={SpinnerComponent}
ErrorView={ErrorComponent}
loadingViewProps={{size: 'large'}}
errorViewProps={{showDetails: true}}
>
{data && <YourContent data={data} />}
</DataLoader>
道具 :
status- 当前装入状态error- 错误对象errorAction- 用于重试错误的函数或动作配置LoadingView- 装入时要显示的组件ErrorView- 错误时要显示的组件loadingViewProps- 向装入视频的道具errorViewProps- 给错误查看的道具
<DataInfiniteLoader />
用于无限查询的专门组件.
<DataInfiniteLoader
status={status}
error={error}
hasNextPage={hasNextPage}
fetchNextPage={fetchNextPage}
isFetchingNextPage={isFetchingNextPage}
LoadingView={SpinnerComponent}
ErrorView={ErrorComponent}
MoreView={LoadMoreButton}
>
{data.map((item) => (
<Item key={item.id} data={item} />
))}
</DataInfiniteLoader>
附加道具 :
hasNextPage- 是否有更多网页可供使用fetchNextPage- 要获取下一页的函数isFetchingNextPage- 是否正在获取下页MoreView- “再装入”按钮组件
withDataManager(Component)
输入 DataManager 作为道具的HOC.
const MyComponent = withDataManager<Props>(({dataManager, ...props}) => {
// Component has access to dataManager
return <div>...</div>;
});
数据管理
ClientDataManager
数据管理主课.
const dataManager = new ClientDataManager({
defaultOptions: {
queries: {
staleTime: 300000, // 5 minutes
retry: 3,
refetchOnWindowFocus: false,
},
},
});
方法:
invalidateTag(tag, options?)
以特定标记取消所有查询.
await dataManager.invalidateTag('users');
await dataManager.invalidateTag('posts', {
repeat: {count: 3, interval: 1000}, // Retry invalidation
});
invalidateTags(tags, options?)
无效所有指定标记的查询 .
await dataManager.invalidateTags(['user', 'profile']);
invalidateSource(dataSource, options?)
无效所有数据源查询.
await dataManager.invalidateSource(userDataSource);
invalidateParams(dataSource, params, options?)
取消带有精确参数的特定查询.
await dataManager.invalidateParams(userDataSource, {userId: 123});
resetSource(dataSource)
为数据源重置( 清除) 所有缓存数据 .
await dataManager.resetSource(userDataSource);
resetParams(dataSource, params)
重置特定参数的缓存数据 .
await dataManager.resetParams(userDataSource, {userId: 123});
invalidateSourceTags(dataSource, params, options?)
基于数据源生成的标记的查询无效 .
await dataManager.invalidateSourceTags(userDataSource, {userId: 123});
公用事业
skipContext(fetchFunction)
用于将现有的获取函数调整到数据源接口的功能.
// Existing function
async function fetchUser(params: {userId: number}) {
// ...
}
// Adapted for data source
const dataSource = makePlainQueryDataSource({
name: 'user',
fetch: skipContext(fetchUser), // Skips context and fetchContext params
});
withCatch(fetchFunction, errorHandler)
添加标准化错误处理以获取函数 .
const safeFetch = withCatch(fetchUser, (error) => ({error: true, message: error.message}));
withCancellation(fetchFunction)
添加取消支持以获取函数 .
const cancellableFetch = withCancellation(fetchFunction);
// Automatically handles AbortSignal from React Query
getProgressiveRefetch(options)
创建渐进回溯间隔函数.
const progressiveRefetch = getProgressiveRefetch({
minInterval: 1000, // Start with 1 second
maxInterval: 30000, // Max 30 seconds
multiplier: 2, // Double each time
});
const dataSource = makePlainQueryDataSource({
name: 'data',
fetch: skipContext(fetchData),
options: {
refetchInterval: progressiveRefetch,
},
});
normalizeStatus(status, fetchStatus)
将 React 查询状态转换为 DataLoader 状态 .
const status = normalizeStatus('pending', 'fetching'); // 'loading'
状态和错误
// Get combined status from multiple states
const status = getStatus([user, posts, comments]);
// Get first error from multiple states
const error = getError([user, posts, comments]);
// Merge multiple statuses
const combinedStatus = mergeStatuses(['loading', 'success', 'error']); // 'error'
// Check if query key has a tag
const hasUserTag = hasTag(queryKey, 'users');
关键组成
// Compose cache key for a data source
const key = composeKey(userDataSource, {userId: 123});
// Compose full key including tags
const fullKey = composeFullKey(userDataSource, {userId: 123});
常数
import {idle} from '@gravity-ui/data-source';
// Special symbol for skipping query execution
const params = shouldFetch ? {userId: 123} : idle;
// Type-safe alternative to enabled: false
// Instead of:
const {data} = useQueryData(userDataSource, {userId: userId || ''}, {enabled: Boolean(userId)});
// Use:
const {data} = useQueryData(userDataSource, userId ? {userId} : idle);
// TypeScript correctly infers types for both branches
查询选项组成
// Compose React Query options for plain queries
const plainOptions = composePlainQueryOptions(context, dataSource, params, options);
// Compose React Query options for infinite queries
const infiniteOptions = composeInfiniteQueryOptions(context, dataSource, params, options);
说明: 这些功能主要用于创建自定义数据源执行时的内部.
高级图案
带离子的有条件查询
使用 idle 以创建条件查询 :
import {idle} from '@gravity-ui/data-source';
const ConditionalDataComponent: React.FC<{
userId?: number;
shouldLoadPosts: boolean;
}> = ({userId, shouldLoadPosts}) => {
// Load user only if userId is defined
const user = useQueryData(
userDataSource,
userId ? {userId} : idle
);
// Load posts only if user is loaded and flag is enabled
const posts = useQueryData(
userPostsDataSource,
user.data && shouldLoadPosts ? {userId: user.data.id} : idle
);
const combined = useQueryResponses([user, posts]);
return (
<DataLoader status={combined.status} error={combined.error}>
<div>
{user.data && <UserInfo user={user.data} />}
{posts.data && <UserPosts posts={posts.data} />}
</div>
</DataLoader>
);
};
数据转换
变换请求参数和响应数据 :
const apiDataSource = makePlainQueryDataSource({
name: 'api-data',
transformParams: (params: {id: number}) => ({
userId: params.id,
apiVersion: 'v2',
format: 'json',
}),
transformResponse: (response: ApiResponse) => ({
user: response.data.user,
metadata: response.meta,
}),
fetch: skipContext(apiFetch),
});
基于标记的缓存无效化
高级缓存管理使用标签 :
const userDataSource = makePlainQueryDataSource({
name: 'user',
tags: (params) => [`user:${params.userId}`, 'users', 'profiles'],
fetch: skipContext(fetchUser),
});
const userPostsDataSource = makePlainQueryDataSource({
name: 'user-posts',
tags: (params) => [`user:${params.userId}`, 'posts'],
fetch: skipContext(fetchUserPosts),
});
// Invalidate all data for specific user
await dataManager.invalidateTag('user:123');
// Invalidate all user-related data
await dataManager.invalidateTag('users');
类型处理出错
创建类型安全错误处理 :
interface ApiError {
code: number;
message: string;
details?: Record<string, unknown>;
}
const ErrorView: React.FC<ErrorViewProps<ApiError>> = ({error, action}) => (
<div className="error">
<h3>Error {error?.code}</h3>
<p>{error?.message}</p>
{action && (
<button onClick={action.handler}>
{action.children || 'Retry'}
</button>
)}
</div>
);
带有复杂插座的无限查询
处理复杂的平面图:
interface PaginationParams {
cursor?: string;
limit?: number;
filters?: Record<string, unknown>;
}
interface PaginatedResponse<T> {
data: T[];
nextCursor?: string;
hasMore: boolean;
}
const infiniteDataSource = makeInfiniteQueryDataSource({
name: 'paginated-data',
fetch: skipContext(async (params: PaginationParams) => {
const response = await fetch(`/api/data?${new URLSearchParams(params)}`);
return response.json() as PaginatedResponse<DataItem>;
}),
next: (lastPage) => {
if (lastPage.hasMore && lastPage.nextCursor) {
return {cursor: lastPage.nextCursor, limit: 20};
}
return undefined;
},
});
合并多个数据源
综合多个来源的数据:
const UserProfile: React.FC<{userId: number}> = ({userId}) => {
const user = useQueryData(userDataSource, {userId});
const posts = useQueryData(userPostsDataSource, {userId});
const followers = useQueryData(userFollowersDataSource, {userId});
const combined = useQueryResponses([user, posts, followers]);
return (
<DataLoader
status={combined.status}
error={combined.error}
errorAction={combined.refetchErrored} // Only retry failed requests
LoadingView={ProfileSkeleton}
ErrorView={ProfileError}
>
{user && posts && followers && (
<div>
<UserInfo user={user.data} />
<UserPosts posts={posts.data} />
<UserFollowers followers={followers.data} />
</div>
)}
</DataLoader>
);
};
类型脚本支持
库用TypeScript-first方法构建,并提供完整的类型推论:
// Types are automatically inferred
const userDataSource = makePlainQueryDataSource({
name: 'user',
fetch: skipContext(async (params: {userId: number}): Promise<User> => {
// Return type is inferred as User
}),
});
// Hook return type is automatically typed
const {data} = useQueryData(userDataSource, {userId: 123});
// data is typed as User | undefined
自定义出错类型
定义和使用自定义错误类型 :
interface ValidationError {
field: string;
message: string;
}
interface ApiError {
type: 'network' | 'validation' | 'server';
message: string;
validation?: ValidationError[];
}
const typedDataSource = makePlainQueryDataSource<
{id: number}, // Params type
{id: number}, // Request type
ApiResponse, // Response type
User, // Data type
ApiError // Error type
>({
name: 'typed-user',
fetch: skipContext(fetchUser),
});
捐款
请阅读 捐款额 详细介绍我们的行为守则和提交拉动请求的程序.
许可证
MIT许可证。 见 自由主义 详细文件.