1.0.7 • Published 1 year ago

rumijs v1.0.7

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

Rumi

Rumi,中文发音为「鲁米」是可扩展的企业级前端应用框架,支持各种功能扩展和业务需求。

Request 的使用方式

Request 是基于axios封装的企业级前端应用HTTP框架,下面我来简单介绍一下 Request 的功能已经使用方式。

1.每一个项目请求服务地址已经业务接口规则都不一样,因此在使用之前我们需要配置自己的 Request 设置。 此工具内提供了useRequestConfig用于配置,它的接收一个回调函数,此函数的回调参数是IRequestConfig类型,而这个回调参数就是默认配置信息。

需要注意:useRequestConfig的回调函数的返回值必须是IRequestConfig类型,IRequestConfig有默认的实现类RequestConfigImpl

let requestConfigImpl = new RequestConfigImpl();
requestConfigImpl.requestOptions.apiUrl = "https://you.server.ip.com";
requestConfigImpl.requestOptions.urlPrefix = "/api"

useRequestConfig((requestConfig: IRequestConfig) => {
  return Object.assign(requestConfig, requestConfigImpl);
})

2.获取useRequest引入到项目中。这个useRequest接收一个IRequestConfig类型的可选参数,返回一个VRequest实例对象。之后我们便能通过此实例发起getpost等请求。

注意:useRequest接收的IRequestConfig类型的参数优先级要高于 useRequestConfig, 此处设置将覆盖useRequestConfig(并非替换)

import { useRequest } from "rumi";
let request = useRequest();
// 或
let requestConfigImpl = new RequestConfigImpl();
requestConfigImpl.requestOptions.apiUrl = "https://you.server.ip.com";
requestConfigImpl.requestOptions.urlPrefix = "/api"
let request = useRequest(requestConfigImpl);

3.定义业务实体接口信息,要继承IBaseEntityIBaseEntityList<E>

// 业务实体类信息
interface UserEntity extends IBaseEntity {
  name: string;
  age: number;
}
// 分页数据
interface UserEntityList extends IBaseEntityList<UserEntity> {
  list: UserEntity[]
}

4.定义业务请求类,这里需要继承IServiceApi<E,L>抽象类,并且重写内部方法。

export class UserServiceApi extends IServiceApi<UserEntity, UserEntityList> {
  list(param?: Params): Promise<Result<UserEntity[]>> {
    return request.get<Result<UserEntity[]>>({
      url: '/list',
      params: param
    });
  }

  page(param: Params): Promise<Result<UserEntityList>> {
    return request.get<Result<UserEntityList>>({
      url: '/page',
      params: param
    });
  }

  detail(id: Params): Promise<Result<UserEntity>> {
    return request.get<Result<UserEntity>>({
      url: `/detail/${id}`,
    });
  }

  save(entity: UserEntity): Promise<Result<UserEntity>> {
    return request.post<Result<UserEntity>>({
      url: `/save`,
      data: entity
    });
  }

  update(entity: UserEntity): Promise<Result<UserEntity>> {
    return request.put<Result<UserEntity>>({
      url: `/update`,
      data: entity
    });
  }

  delete(ids: Params): Promise<Result> {
    return request.delete<Result>({
      url: `/delete`,
      params: ids
    });
  }

  sort(id: Params, param: Params): Promise<Result> {
    return request.get<Result>({
      url: `/sort/${id}`,
      params: param
    });
  }
}

5.调用业务api

const userServiceApi = new UserServiceApi();
async function getUserList() {
  const result = await userServiceApi.list({ age: 18 });
  const { data, code, msg } = result;
}

function getUserPage() {
  userServiceApi.page({ page: 18 }).then((result) => {
    const { data, code, msg } = result;
  })
}

如果以上的接口不符合你们的业务需求,可继承接口继续扩展或是修改它们,具体的接口信息请看 API 介绍

Api介绍

IRequestConfig

Request 配置接口,此接口默认继承了 Axios 的请求配置接口,其默认实现类RequestOptionsConfigImpl

interface IRequestConfig<D = FormDataParams> extends AxiosRequestConfig<D> {
  /**
   * 令牌前缀 默认:'Bearer'
   * https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#authentication_schemes
   * */
  authenticationScheme?: string;
  /** 超时时间 默认:10S */
  timeout: number;
  /** 是否允许携带Cookie 默认:false */
  withCredentials: boolean;
  /** 请求头 默认:{ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' } */
  headers: Record<string, string>;
  /** 数据处理 */
  transform?: IRequestTransform;
  /** 中央控制器配置选项 */
  requestOptions: IRequestOptionsConfig;
}

IRequestTransform

Request 中央控制器请求核心处理类。

interface IRequestTransform {
  /** 请求前处理配置 Hook */
  beforeRequestHook?: (config: IRequestConfigWithOptional, options: IRequestOptionsConfig) => IRequestConfigWithOptional;

  /** 请求前的拦截器 */
  requestInterceptors?: (
    config: IRequestConfigWithOptional,
    options: IRequestConfig,
  ) => IRequestConfigWithOptional;

  /** 请求响应拦截器处理 */
  responseInterceptors?: (res: AxiosResponse, options: IRequestOptionsConfig) => Promise<AxiosResponse>;

  /** 转换前 Hook;处理请求数据。如果数据不是预期格式,可直接抛出错误 */
  transformResponseHook?: (res: ResponseResult, options: IRequestOptionsConfig) => BaseResponseResult;

  /** 请求响应的拦截器错误处理 */
  responseInterceptorsCatch?: (error: AxiosError) => Promise<ResponseError>;

  /** 请求失败处理 */
  requestCatchHook?: (e: ResponseError, options: IRequestOptionsConfig) => ResponseError;

  /** 请求前的拦截器错误处理 */
  requestInterceptorsCatch?: (error: AxiosError) => Promise<AxiosError>;
}

IRequestOptionsConfig

此接口则是请求的配置。

interface IRequestOptionsConfig {
  /** 接口地址 默认:http://localhost:8080 */
  apiUrl?: string;
  /** 是否自动添加接口前缀 默认:false */
  isJoinPrefix?: boolean;
  /** 接口前缀 默认:/api */
  urlPrefix?: string;
  /** post请求的时候添加参数到url 默认:false */
  joinParamsToUrl?: boolean;
  /** 格式化提交参数时间 默认:true */
  formatDate?: boolean;
  /** 不进行任何处理,直接返回 Response 数据 默认:false */
  isTransformResponse?: boolean;
  /** 是否返回原生响应头 比如:需要获取响应头时使用该属性 默认:false */
  isReturnNativeResponse?: boolean;
  /** 是否加入时间戳 默认:false */
  joinTime?: boolean;
  /** 是否携带token 默认:false */
  withToken?: boolean;
  /** 令牌在Header头部的字段。 若未设置 fieldToken 则默认:Authorization */
  fieldToken?: string;
  /** 忽略重复请求 默认:false */
  ignoreRepeatRequest?: boolean;
  /** 是否需要防止数据重复提交 默认:false */
  isRepeatSubmit?: boolean;
  /** 重试 */
  retry?: {
    /** 重试次数 默认3次 */
    count: number;
    /** 重试间隔时间 1S */
    delay: number;
  };
  /** debugger模式 默认:false */
  isDebugger?: boolean;
}

IServiceApi

IServiceApi抽象类,用于定义业务接口请求方法,在使用的时候重写此方法即可。

abstract class IServiceApi<T extends IBaseEntity, L extends IBaseEntityList<T>> {
  list(param?: Params): Promise<Result<T[]>>{}
  page(param: Params): Promise<Result<L>> {}
  detail(id: Params): Promise<Result<T>> {}
  save(entity: T): Promise<Result<T>> {}
  update(entity: T): Promise<Result<T>> {}
  delete(ids: Params): Promise<Result> {}
  sort(id: Params, param: Params): Promise<Result> {}
}

IBaseEntity

业务数据基类

  interface IBaseEntity {
    createTime?: unknown;
    updateTime?: unknown;
    [key: string]: any;
  }

IBaseEntity

业务数据分页列表实体类型继承IPageInfo

  interface IBaseEntityList<T extends IBaseEntity> extends IPageInfo {
    list: T[];
  }

Entity

实体顶类型

  type Entity = IBaseEntity | IBaseEntityList<IBaseEntity>;

IPageInfo

分页接口

  interface IPageInfo {
    [key: string]: any;
    /** 总页数 */
    totalCount: number;
    /** 当前页数 */
    currPage: number;
    /** 上一页 */
    prePage: number;
    /** 下一页 */
    lastPage: number;
  }

Params

请求参数类型

  type Params =
    | number
    | string
    | boolean
    | Record<string, any>
    | Recordable
    | number[]
    | string[]
    | boolean[]
    | Record<string, any>[]
    | Recordable[];

FormDataParams

FormData 类型

type FormDataParams = Record<any, any> | Recordable;

IDefaultResult

默认响应实体接口

interface IDefaultResult<T extends typeof Entity = Entity> {
  [key: string]: any;
  code: number;
  data: T;
  msg: string;
}

IServiceResult

自定义响应实体接口

interface IServiceResult<T extends typeof Entity = Entity> {
  [key: string]: any;
}

Result

请求响应结果集接口

type Result<T extends typeof Entity = Entity> = IDefaultResult<T> | IServiceResult<T>;
1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago