fix: will fetch 按照协议修改

This commit is contained in:
guokai.jgk 2020-10-23 11:30:38 +08:00
parent af4bc83cc3
commit b9bf8002dc
3 changed files with 23 additions and 11 deletions

View File

@ -106,12 +106,18 @@ class RuntimeDataSourceItem<
return;
}
let fetchOptions = this._options;
// willFetch
this._dataSourceConfig.willFetch!();
try {
fetchOptions = await this._dataSourceConfig.willFetch!(this._options);
} catch (error) {
console.error(error);
}
// 约定如果 params 有内容,直接做替换,如果没有就用默认的 options 的
if (params && this._options) {
this._options.params = params;
if (params && fetchOptions) {
fetchOptions.params = params;
}
const dataHandler = this._dataSourceConfig.dataHandler!;
@ -124,7 +130,7 @@ class RuntimeDataSourceItem<
// _context 会给传,但是用不用由 handler 说了算
const result = await (this._request as RequestHandler<{
data: TResultData;
}>)(this._options, this._context).then(dataHandler, errorHandler);
}>)(fetchOptions, this._context).then(dataHandler, errorHandler);
// setState
this._context.setState({

View File

@ -1,7 +1,8 @@
import { DataHandler } from '@ali/lowcode-types';
// eslint-disable-next-line @typescript-eslint/no-empty-function
function noop() {}
import {
DataHandler,
RuntimeOptionsConfig,
WillFetch,
} from '@ali/lowcode-types';
// 默认的 dataSourceItem 的 dataHandler
export const defaultDataHandler: DataHandler = async <T = unknown>(response: {
@ -9,7 +10,8 @@ export const defaultDataHandler: DataHandler = async <T = unknown>(response: {
}) => response.data;
// 默认的 dataSourceItem 的 willFetch
export const defaultWillFetch = noop;
export const defaultWillFetch: WillFetch = (options: RuntimeOptionsConfig) =>
options;
// 默认的 dataSourceItem 的 shouldFetch
export const defaultShouldFetch = () => true;

View File

@ -14,7 +14,7 @@ export interface RuntimeDataSourceConfig {
isInit?: boolean;
isSync?: boolean;
type?: string;
willFetch?: () => void;
willFetch?: WillFetch;
shouldFetch?: () => boolean;
requestHandler?: () => void; // TODO: 待定
dataHandler?: DataHandler;
@ -23,6 +23,10 @@ export interface RuntimeDataSourceConfig {
[otherKey: string]: unknown;
}
export type WillFetch = (
options: RuntimeOptionsConfig,
) => Promise<RuntimeOptionsConfig> | RuntimeOptionsConfig;
export type DataHandler = <T>(response: {
data: T;
[index: string]: unknown;
@ -45,7 +49,7 @@ export interface RuntimeOptionsConfig {
// 可以采用 react 的 state但是需要注意必须提供同步的 setState 功能
export interface IDataSourceRuntimeContext<
TState extends Record<string, unknown> = Record<string, unknown>
> {
> {
/** 当前数据源的内容 */
state: TState;
/** 设置状态(浅合并) */