@zenview/micro-basic-library

0.9.1 • Public • Published

简介

micro-basic-library 是通用接口、状态、方法服务,里面封装了如 "Dict" 字典类、“store” mobx 全局状态类、“shared”共享业务方法类、“LMConfig”配置类、“service”公共接口方法类,使用微应用脚手架构建项时目已默认安装,可直接使用。

Git 仓库地址:https://git.topvdn.com/micro-basic/micro-basic-library

依赖安装:

//示例为yarn安装,也可以使用npm安装
yarn add @zenview/micro-basic-library

使用示例:

//使用示例
import { BaseStore,LMConfig,Dict } from '@zenview/micro-basic-library';

function UserView(){
  //Dict字典hooks使用 useDicts传入要获取的字典类code
  const [sex, userStatus] = Dict.useDicts(['100000', '104400'])
  //获取BaseStore下用户性别code 根据字典过滤出性别
  const sexTetx = sex.find((v) => v.value === BaseStore.app.userInfo.userSex);
  //调用系统配置
  const text = 默认查询近{LMConfig.BSConfig.dataRetention}

  return <>{text}/性别:{sexTetx ||'男'}</>
}

LMConfig

配置信息公共类

代码演示

import { LMConfig } from '@zenview/micro-basic-library';
...
  useEffect(() => {
    //判断是否开启webSocket
    LMConfig.BSConfig.openSocket && SocketEmitter.connect('/socket.io',null);
    // 存放播放插件版本
    sessionStorage.setItem('_APP_PLAY_VERSION', LMConfig.BSConfig.player.version)
  }, []);

  //获取地图配置中心点
const center = LMConfig.LMapConfig.layerOptions.center
...

API

type ConfigJOSN = { [key: string]: any };

export interface LMConfigInterface {
  BSConfig: ConfigJOSN;
  LMapConfig: ConfigJOSN;
}

declare const LMConfig: LMConfigInterface;
参数 说明
BSConfig 系统配置
LMapConfig 地图配置

Service

接口公共类

代码演示

import { Service } from '@zenview/micro-basic-library';
import { cache } from '@zenview/micro-utils';
Service.$http({
  requestId: 'AlarmResult',
  headers: {
    Authorization: cache.getCache('token', 'session'),
  },
  url: '/handleAlarmResult',
  data,
  method: 'post',
  requestId: 'handleAlarmResult',
})
  .then((res) => {
    Service.logger.save({
      function: 105201,
      module: 105200,
      description: `查看重点人员布控告警信息,信息ID:${id}`,
    });
    return res;
  })
  .catch((e) => {
    return Promise.reject(e);
  });

API

export type loggerType = {
  save(options: { description: string; module: string | number; function: string | number }, token?: string): Promise<any>;
};
export interface ServiceInterface {
  $http(options: AxiosRequestConfig & { requestId?: string; cancelHttp?: (cancel: Function) => void }): Promise<any>;
  $httpXMLInstance(options: AxiosRequestConfig & { requestId?: string; loggerIndex?: number }): Promise<any>;
  $httpMultiPartInstance(options: AxiosRequestConfig): Promise<any>;
  logger: loggerType;
}

declare const Service: ServiceInterface;
参数 说明
$http 基于 axios 封装的 ajax 请求方法
$httpXMLInstance XML 请求方式
$httpMultiPartInstance formData 文件传输请求
logger 基于$http 封装的记录日志请求

Options

参数 说明 类型
url 请求地址 string
headers 请求偷 any
method 请求方式 string
requestId 请求接口对应唯一标识 string

Dict

字典存取公共类 注意:Dict 获取字典第一次输入的 code 因为是请求接口异步获取,所以 hook 方法在某些场景可能会出现获取后未响应的情况,可使用 useMemo 进行再次包裹监听:代码示例

代码演示

hooks 函数组件用法
class 装饰器用法
import { Dict } from '@zenview/micro-basic-library';
const dictCode = ['119100', '119113', '119104', '119109'];
//withDict写入要获取的字典类code
@Dict.withDict(dictCode)
class DeviceInfo extends React.Component {
  constructor(props) {
    super(props);
    // props.dictMap 根据字典类code读取对应字典
    if (props.dictMap) {
      let arr = [];
      for (const key of dictCode) {
        props.dictMap[key] && (arr = [...arr, ...props.dictMap[key]]);
      }
      this.placeType = arr;
    }
  }
  render() {
    let { pathId = [] } = this.props;
    const tagLabel = this.placeType.filter((v) => pathId.indexOf(v.code) > -1);

    return <TagView tags={tagLabel} />;
  }
}
device 类字典用法
import { Dict } from '@zenview/micro-basic-library';
...
//过滤摄像机类型
const cameraTypes = []
    if (Dict.device.deviceType) {
      const deviceType = Dict.device.deviceType;
      deviceType
        .filter((v) => v.value !== '-1' && v.value !== '100605')
        .map((v) => {
          let item = v.value.split(',');
          if (item.length > 1) {
            cameraTypes.push(item[0]);
            cameraTypes.push(item[1]);
          } else {
            cameraTypes.push(v.value);
          }
          return cameraTypes;
        });
}
/**根据设备类型和状态获取设备展示图标 */
const { znxj, qj, db, wifi, mj, wgsb, dz, xfs, znjg, qt } = Dict.device;
const { ptjk, rlzp, zpj, clzpj, qmbzpj, ydjc, qtzp } = Dict.device;

export const getCameraTypeIcon = (type, status) => {
  const onLine = status * 1 === 1;
  let option = {};
  if (znxj.value === type) {
    option.url = znqjimg;
    option.color = !onLine ? '#ccc' : 'rgba(255, 156, 84, 1)';
    option.bgColor = !onLine ? '#ccc' : '#29CCCC';
    option.icon = 'icon-S_Point_Smart';
  }
  if (qj.value === type) {
    option.url = qjimg;
    option.color = !onLine ? '#ccc' : 'rgba(43, 153, 255, 1)';
    option.bgColor = !onLine ? '#ccc' : '#29CCCC';
    option.icon = 'icon-S_Point_Ball';
  }
  if (zpj.value === type) {
    option.url = zpjimg;
    option.color = !onLine ? '#ccc' : 'rgba(193, 100, 207, 1)';
    option.bgColor = !onLine ? '#ccc' : '#29CCCC';
    option.icon = 'icon-S_Point_Gun';
  }
  ...
  }
特殊情况处理示例
import React, { useMemo } from 'react';
import { Dict } from '@zenview/micro-basic-library';
import typeCode from '../../typeCode'
//hooks 中字典特殊情况处理
//字典code获取
const dictCode = (name)=>{
   const obj = typeCode.find(v=>name===v.name)
   return obj?.code ? obj.code : undefined
}
//表单组件赋值
function FormItems({ onChange, value, item, isInfo }) {
  const code = dictCode(item.dict)
  const useDict = Dict.useDict(item.dicType === 'local'? code : undefined)
  //判断字典获取方式'local'本地读取,'url'请求接口,'setting'手动配置
  const dicfilter = useMemo(() => {
    if (item.dicType) {
      switch (item.dicType) {
        case 'setting':
          return item.dicData;
        case 'local':
          return useDict
        case 'url':
          return [];
        default:
          return [];
      }
    } else {
      return item.dicData || [];
    }
  }, [item.dicType,item.dicData,useDict]);
  ...
  }

API

interface DictItem {
  label: string;
  code: string;
  id: string;
  icon: string;
}

interface DeviceDict {
  deviceStatus: Array<DictItem>;
  deviceLocation: Array<DictItem>;
  cameraType: Array<DictItem>;
  cameraDeviceType: Array<DictItem>;
  cameraAndSoldierType: Array<DictItem>;
  deviceAndMjType: Array<DictItem>;
  deviceType: Array<DictItem>;
  [key: string]: DictItem;
}
declare type IReactComponent<P = any> = React.ClassicComponentClass<P> | React.ComponentClass<P> | React.FunctionComponent<P> | React.ForwardRefExoticComponent<P>;
declare type IWrappedComponent<P> = {
  wrappedComponent: IReactComponent<P>;
};
interface DictMapProps {
  dictMap: { [key: string]: Array<DictItem> };
}

export interface DictInterface {
  useDict(typeCode: string | number): Array<DictItem & any>;
  useTypeCodes(): Array<DictItem & any>;
  useDicts(typeCodes: Array<string | number>): Array<Array<DictItem & any>>;
  device: DeviceDict;
  withDict(code: Array<string | number>): <T extends IReactComponent<any>>(target: T) => T & (T extends IReactComponent<infer P & DictMapProps> ? IWrappedComponent<P & DictMapProps> : never);
  withTypeCodes<T extends IReactComponent>(component: T): T;
}

declare const Dict: DictInterface;
参数 说明
useDict code 获取单个字典 hooks
useDicts codes 批量获取字典 hooks
withDict 装饰器 codes 批量获取字典
device 设备类字典
useTypeCodes 获取结构化信息类型字典 hooks
withTypeCodes 装饰器获取结构化信息类型字典

BaseStore

全局状态管理 注意:BaseStore 类中方法使用方式分为 import 引入和 mobx 注入两种,对应不同使用场景,import 引入在数据状态全局更新时 不会触发重新渲染,mobx 反之。

代码演示

//应用组件外层注入BaseStore 同mobx使用方法
import { BaseStore } from '@zenview/micro-basic-library';
<Provider {...BaseStore}>...</Provider>;
//组件中mobx方式使用 以下为函数组件参考,class组件请参考mobx API
import { inject, observer } from 'mobx-react';

function OrgView({org}){...}

export default inject('org')(observer(OrgView));
import { BaseStore } from '@zenview/micro-basic-library';
//组件中BaseStore引用方式使用
function BaseInfo() {
  const userInfo = BaseStore.app.userInfo;
}

API

export interface BaseStoreInterface {
  device: typeof DeviceStore;
  org: typeof OrgStore;
  place: typeof PlaceStore;
  app: typeof AppStore;
  auth: typeof AuthStore;
}
参数 说明
app 用户信息类
auth 菜单权限类
device 设备信息类
org 组织信息类
place 场所信息类

app

用户信息全局状态

代码演示

//示例为mobx方式
import { inject, observer } from 'mobx-react';

function MenuView({app}) {
  ...
  return (
    <div className="title">
        <p>您好{app.userInfo?.loginName},欢迎来到</p>
        <h3>{app.systemConfig?.systemName}</h3>
      </div>
  )
}

export default inject('app')(observer(MenuView));

API

export interface UserInfo {
  loginName: string;
  id: string;
  operationCenterId: string;
  organizationId: string;
  phoneNum: string;
  realName: string;
  roleIds: Array<string>;
  systemLogo: string;
  userGrade: string;
  userSource: string;
  userType: string;
  validStartTime: string;
  validEndTime?: string;
  validState: string;
  mobile: string;
  email?: string;
  userSex: string;
  identityCardNum: string;
  telephone?: string;
  addressCode?: string;
}

export interface AppInfo {
  centerPoint: string;
  centerType: string;
  id: string;
  isHideLogo: string;
  operationCenterName: string;
  sceneCode: string;
  sceneType: string;
  systemLogoUrl: string;
  userInitialPassword: string;
  zoomLevelCenter: string;
}

export interface SystemConfig {
  centerPoint: string;
  domainAddress: string;
  systemLogo: string;
  systemName: string;
  zoomLevelCenter: string;
}

export interface AppStoreInterface {
  isLogin: boolean;
  appInfo: AppInfo;
  userInfo: UserInfo;
  systemConfig: SystemConfig;
  updateLoginStatus: (loginStatus: boolean) => void;
}

declare const AppStore: AppStoreInterface;
参数 说明
isLogin 获取登录状态
appInfo 用户登录信息
userInfo 用户信息
systemConfig 用户系统信息
updateLoginStatus 更新登录状态

auth

用户信息全局状态

代码演示

//示例为BaseStore方式
import { BaseStore } from '@zenview/micro-basic-library';

function MenuView() {
  const {auth} = BaseStore
  const menuList = auth.userMenuList.filter((v) => v.type !== 0);
  const isBool= auth.getInfoByName(item.id));
}

API

export interface FeatureItem {
  code: number;
  parentCode?: number;
  id: string;
  sort: number;
  name: string;
  isMenu: number;
  alias: string;
  routeUrl: string;
  requestParam?: string;
  microApplicationId: string;
  applicationSystemId: string;
}

export const authStore: { dataMap: Map<string, FeatureItem>; nameToCode: Map<string, number>; codeToName: Map<number, string> };

export interface AuthStoreInterface {
  userMenuList: Array<FeatureItem>;
  userAuthList: Array<FeatureItem>;
  isAuth(name: string): boolean;
  getInfoByCode(code: number): FeatureItem;
  getInfoByNames(names: string[]): Array<FeatureItem>;
  getInfoByName(name: string): FeatureItem;
}

declare const AuthStore: AuthStoreInterface;
参数 说明
userMenuList 用户菜单列表
userAuthList 用户菜单及功能全列表
isAuth 根据别名判断是否有权限
getInfoByCode 根据 code 返回当前菜单功能信息
getInfoByNames 根据 codes 批量返回当前菜单功能信息

device

设备信息全局状态

代码演示

import { BaseStore } from '@zenview/micro-basic-library';
//
const deviceList = BaseStore.device.deviceList;
const currentList = BaseStore.device.queryDeviceByIncludeOrgId(id);

API

export type DeviceItemType = {
  abilityIds: [];
  cameraOrientationCode: string;
  cameraType: string;
  cid: string;
  deviceName: string;
  deviceStatus: '0' | '1';
  deviceType: string;
  hasFrontEnd: boolean;
  hasStorage: boolean;
  id: string;
  latitude: string;
  longitude: string;
  lygroupId: string;
  manufacturerDeviceId: string;
  manufacturerDeviceType: string;
  organizationIds: Array<string>;
  parentId: string;
  placeId: string;
  sn: string;
};

export const deviceStore: {
  dataMap: Map<string, DeviceItemType>;
  idToCid: Map<string, string>;
  cidToId: Map<string, string>;
};

export interface DeviceStoreInterface {
  cameraList: Array<DeviceItemType>;
  deviceList: Array<DeviceItemType>;
  initSetDevices(mapData: { [key: string]: DeviceItemType }): void;
  updateSingleDevice(info: DeviceItemType & { deviceId: string; type: number }): void;
  updateMutipleDevice(infos: Array<DeviceItemType & { deviceId: string; type: number }>): void;
  getDeviceById(id: string): DeviceItemType | undefined;
  getDeviceByCId(cid: string): DeviceItemType | undefined;
  getDeviceByIds(ids: string[]): Array<DeviceItemType>;
  getDeviceByCIds(cids: string[]): Array<DeviceItemType>;
  getListByIdsOrCids(idOrCids: string[]): Array<DeviceItemType>;
  queryCameraByIncludeOrgId(orgId: string, cameraList?: Array<DeviceItemType>);
  queryDeviceByIncludeOrgId(orgId: string, deviceList?: Array<DeviceItemType>);
  queryCameraByIncludePlaceId(placeId: string, cameraList?: Array<DeviceItemType>);
}
declare const DeviceStore: DeviceStoreInterface;
参数 说明
cameraList 摄像机列表
deviceList 设备列表
initSetDevices 初始化设备
updateSingleDevice 单个更新设备
updateMutipleDevice 批量更新设备
getDeviceById 单个 ID 获取设备信息
getDeviceByCId 单个 CID 获取设备信息
getDeviceByIds IDS 批量获取设备信息
getDeviceByCIds CIDS 批量获取设备信息
getListByIdsOrCids 获取批量设备信息
queryCameraByIncludeOrgId 查询组织下摄像机列表(含子组织)
queryDeviceByIncludeOrgId 查询组织下设备列表(含子组织)
queryCameraByIncludePlaceId 查询场所下设备列表(含子组织)

org

用户组织信息全局状态

代码演示

import { inject, observer } from 'mobx-react';
import { BaseStore } from '@zenview/micro-basic-library';
import { treeHelper } from '@zenview/micro-utils';
function OrgTreeView({org,id}) {

  const treeData = treeHelper.computTreeList(org.orgList)
  const title = BaseStore.org.getOrgTreeText(id);
  ...
}

export default inject('org')(observer(OrgTreeView));

API

export interface OrgItemType {
  createTime: string;
  id: string;
  orgSort: number;
  parentId: string;
  type: string;
  name: string;
}

export const orgStore: { dataMap: Map<string, OrgItemType> };

export interface OrgStoreInterface {
  orgList: Array<OrgItemType>;
  orgListWithCameraCount: Array<OrgItemType>;
  initSetOrgData(orgList: Array<OrgItemType>): void;
  updateSingleOrg(org: OrgItemType): void;
  queryOrgIdsForParentOrgId(orgId: string, ids?: Array<string>, orgList?: Array<OrgItemType>): Array<string>;
  getOrgInfoByOrgId(orgId: string): OrgItemType;
  getOrgTreeText(orgId: string): string;
  getParentOrgListByOrgId(orgId: string, list?: Array<OrgItemType>, orgList?: Array<OrgItemType>);
  getOrgListCount(orgList?: Array<OrgItemType>, deviceList: Array<Device>);
}

declare const OrgStore: OrgStoreInterface;
参数 说明
orgList 组织列表
orgListWithCameraCount 包含像机数量组织列表
initSetOrgData 初始化组织
updateSingleOrg 更新组织数据
queryOrgIdsForParentOrgId 获取组织下的所有组织 id
getOrgInfoByOrgId 单个 ID 获取组织信息
getOrgTreeText 格式化获取父组织名称
getParentOrgListByOrgId 根据 id 获取所有父级组织
getOrgListCount 获取组织下设备数量

place

场所信息全局状态

代码演示

import { inject, observer } from 'mobx-react';
@inject('place')
@observer
class PlaceTree extends React.Component {
  ...
    onChange = (value) => {
    const { place } = this.props;
    const placeList = place.placeList.filter((v) => v.name.indexOf(value) > -1);
  };
  ...
}

export default PlaceTree;

API

export type PlaceItemType = {
  areaCode: string;
  areaName: string;
  center: string;
  hasDevice: boolean;
  id: string;
  level: number;
  name: string;
  parentCode: string;
  placeId: string;
  pcodes?: Array<string>;
  provinceId: string;
  placeInfoUrl?: string;
};
export const placeStore: { dataMap: Map<string, PlaceItemType>; idToCode: Map<string, string>; codeToId: Map<string, string> };
export interface PlaceStoreInterface {
  placeList: Array<PlaceItemType>;
  placeListWithCameraCount: Array<PlaceItemType>;
  placeListWithDeviceCount: Array<PlaceItemType>;
  updateMutiplePlace(list: Array<PlaceItemType>): void;
  initSetPlaceData(list: Array<PlaceItemType>): void;
  getPlaceInfoByCode(code: string): PlaceItemType;
  getPlaceInfoByCodes(codes: string[]): Array<PlaceItemType>;
  getPlaceInfoById(id: string): PlaceItemType;
  getPlaceInfoByIds(ids: string[]): Array<PlaceItemType>;
  getCodesForIds(ids: string[]): Array<string>;
  getIdsForCodes(codes: string[]): Array<string>;
  getPlaceListForIdsOrCodes(idOrCodes: string[]): Array<string>;
  getPlaceCodesWithParent(areaCode: string, areaCodes?: string[]): Array<string>;
  getPlaceCodesWithChild(areaCode: string, areaCodes?: string[], placeList?: Array<PlaceItemType>): Array<string>;
  queryChildPlaceForLevel(areaCode: string, level: number, list?: PlaceItemType[], placeList?: PlaceItemType[]): PlaceItemType[];
  getParentPlaceListByCode(areaCode: string, list?: PlaceItemType[], placeList?: PlaceItemType[]): PlaceItemType[];
  getPlaceListDeviceCount(placeList: PlaceItemType[], deviceList: Device[], type: string);
}
declare const PlaceStore: PlaceStoreInterface;
参数 说明
placeList 场所列表
placeListWithCameraCount 包含像机数量场所列表
placeListWithDeviceCount 包含设备数量场所列表
updateMutiplePlace 更新场所数据
initSetPlaceData 初始化场所数据
getPlaceInfoByCode code 单个获取详细信息
getPlaceInfoByCodes codes 批量获取详细信息
getPlaceInfoById id 单个获取详细信息
getPlaceInfoByIds ids 批量获取详细信息
getCodesForIds id areaCode 转换
getPlaceListForIdsOrCodes id areaCode 转换
getPlaceCodesWithParent 获取场所下的所有场所 codes
getPlaceCodesWithChild 根据 code 获取所以子场所
queryChildPlaceForLevel 获取场所下的所有场所 id
getParentPlaceListByCode 根据 code 获取所有父级场所
getPlaceListDeviceCount 计算场所设备

Shared

公共共享方法

代码演示

import { Shared } from '@zenview/micro-basic-library';

//跳转人脸图库
Shared.jumpFaceLibrary({ this.props.history, cids: ['121234'] });
//发起视频下载审批
Shared.downloadVideo(options)

API

interface jumpFaceLibrary {
  history: H.History<any>;
  [propName: string]: any;
}

interface jumpParm {
  history: H.History<any>;
  defaultItem?: any;
  defaultUrl?: string;
  frameUrl?: string;
  rects?: RectType;
  feature?: string;
  id?: string;
  imgId?: string;
  startTime?: string;
  endTime?: string;
  score?: number;
  cids?: Array<string>;
  aids?: Array<string>;
  type?: string;
}

interface jumpLibraryDetail<T> {
  history: H.History<any>;
  list: Array<T>;
  data?: any;
  currentId: string;
  searchUrl?: string; //搜图传url
  type: 'faceDetail' | 'bodyDetail' | 'faceSearchDetail' | 'bodySearchDetail' | 'vehicleDetail' | 'nonVehicleDetail';
  beforeAction?: () => void;
}

interface jumpTrajectory<T> {
  history: H.History<any>;
  list: Array<T>;
  type: 'faceTrajectory' | 'bodyTrajectory' | 'vehicleTrajectory' | 'nonVehicleTrajectory';
}

interface queryVehicleTrajectoryPictures<T> {
  history: H.History<any>;
  data: any;
  type: 'queryVehicleTrajectoryPictures';
}

interface jumpVehicleSearch<T> {}
interface jumpNonVehicleSearch<T> {}

interface downloadVideo<T> {
  startTime: string;
  endTime: string;
  fileData: {
    id?: string | number;
    cid?: string | number;
    title?: string;
    deviceName?: string;
    [properName: string]: any;
  };
  HistoryService?: (data: any) => Promise<any>;
  onError?: (msg: string) => void;
}

interface formatRectInfo<T> {
  structuredInfo: any;
  dicts: any;
  id: string;
  typeCodes: any;
}
export interface SharedInterface {
  jumpFaceLibrary: jumpFaceLibrary;
  jumpBodyLibrary: jumpFaceLibrary;
  jumpFaceSearch: jumpParm;
  jumpFaceRecord: jumpParm;
  jumpBodySearch: jumpParm;
  jumpBodyRecord: jumpParm;
  jumpLibraryDetail: jumpLibraryDetail;
  jumpTrajectory: jumpTrajectory;
  queryVehicleTrajectoryPictures: queryVehicleTrajectoryPictures;
  jumpCameraSnapshot: jumpFaceLibrary;
  jumpVehicleSearch: jumpVehicleSearch;
  jumpNonVehicleSearch: jumpNonVehicleSearch;
  jumpVehicleLibrary: any;
  jumpNonVehicleLibrary: any;
  resourcePageInfo: any;
  handleResourceListParams: any;

  downloadVideo: downloadVideo;
  formatRectInfo: formatRectInfo;
}

declare const Shared: SharedInterface;
参数 说明
jump**** 跳转类方法
downloadVideo 发起视频下载审批
formatRectInfo 结构化信息 tag

Readme

Keywords

none

Package Sidebar

Install

npm i @zenview/micro-basic-library

Homepage

/

Weekly Downloads

7

Version

0.9.1

License

none

Unpacked Size

571 kB

Total Files

69

Last publish

Collaborators

  • huangjingjing1990
  • feifeizheng
  • jinword
  • chenhao6263