npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cefc-biz-utils

v0.0.24

Published

业务公共 utils

Downloads

11

Readme

cefc-biz-utils

Bridge

.open(url, title)

开启新的 WebView 打开 url,设置标题为 title(默认为页面标题)

.close()

关闭当前 WebView

.exit()

退出 SDK,回到接入方界面

.oac()

进入开户流程界面

.scanIDCard(ok, fail)

扫描身份证

.video(options, ok, fail)

开始双向视频

Data

user, oac, meta 均存于内存; Fields 存于 localStorage

.getUser()

获取用户信息

.setUser(user)

设置用户信息

.getOAC()

获取开户状态信息

.setOAC(oac)

设置开户状态信息

.getAppMeta()

获取应用描述信息

.setAppMeta(meta)

设置应用描述信息

Fields

  • SHAREHOLDER_NOS 股东账号
  • CLIENT_NO 客户号
  • MOBILE 手机号
  • SETTINGS 系统偏好设置

.get(field)

.set(field, val)

.getShareholderNo(marketType)

根据市场类型获取股东账号

  • 深圳SZ - '0'
  • 上海SH - '1'
  • 香港HK - '2'

Log

Example

// 程序入口
function reporter(data) {
  axios({
    method: 'post',
    url: '/stats/log',
    data
  });
}
Log.init(reporter);

// 程序其他部分
Log.info({ msg: 'xxx' });

.init(reporter)

.warn()

.error()

.info()

.debug()

.trace()

.genTpHeader(config)

生成三方渠道的 header 参数,签名、接口统计、用户标识信息

  • config Request config 对象

Tracker

Example

import Tracker from 'cefc-biz-utils/lib/tracker';

if (process.env.NODE_ENV === 'production') {
  // 上传数据函数
  function upload(headers, data) {
    axios({ method: 'post', url: '/stats/track', headers, data });
  }

  // 页面停留时间监控
  history.listen(() => {
    Tracker.pageView(upload);
  });
}

.pageView(reporter)

页面切换时统计页面停留时间

.genTrackStat()

生成接口统计所需的 Header 参数

{
  // 一次会话一个 ID,最好在 Node Server 端生成
  // 目前每加载一次页面会生成一个 ID,并不是一次会话一个 ID
  // 因为 Node Server 端多进程没有共享 Session
  requestAppId: SESSION_ID,
  pageid: window.location.href,
  uuid: uuid(),
  requestTime: Date.now()
}

ReduxStore

配置 store 及动态添加 reducers

Example

import configureStore, { addReducer } from 'cefc-biz-utils/lib/redux-store';

const store = configureStore(initialState || {}, { history, request, ... });

function aActionCreator() {
  return (dispatch, history, request, ...) {
    request.get('https://xxx.com/a/b')
      .then(res => {
        history.push({ pathname: '/home', search: '?the=query', state: { some: 'state' } };
      });
  }
}

addReducer(store, reducers);

Redux 文件示例

import { getUser } from 'cefc-biz-utils/lib/data';
import { Path, Method } from './config/api';

const ActionType = {
  QUERY_ASSETS: 'QUERY_ASSETS',
  CONFIG_BIZ_HOME: 'CONFIG_BIZ_HOME'
};

function queryAssets() {
  return (dispatch, request) => {
    const { fundId } = getUser();

    return request.post(Path.SAS, {
      method: Method.ASSETS_QUERY,
      fundId,
      moneyType: '0'
    }).then((ret) => {
      const asset = ret[0];

      dispatch({
        type: ActionType.QUERY_ASSETS,
        data: {
          totalAmount: asset.allAsset,
          marketAmount: asset.stkValue,
          profitAmount: asset.profitCost,
          expendableFund: asset.fundAvl,
          fundId: asset.fundId
        }
      });
    });
  }
}

function queryNotices() {
  const { fundId } = getUser();
  return (dispatch, request) => {
    return request.post(Path.NEWS, {
      method: Method.GET_NOTICE,
      fundId
    }).then((ret) => {});
  }
}

/**
 * 约定 configure 设置静态的 state, 一般是临时固定在前端的数据
 */
function configure(data) {
  return {
    type: ActionType.CONFIG_BIZ_HOME,
    data
  }
}

// 约定默认导出所有 actions
export default { queryAssets, queryNotices, configure };

const initialState = {
  assets: {
    fundId: null,
    totalAmount: 0,
    marketAmount: 0,
    profitAmount: 0,
    expendableFund: 0
  },
  banner: '',
  menus: []
};

function home(state = initialState, action) {
  const { type, data } = action;

  switch (type) {
    case ActionType.CONFIG_BIZ_HOME:
      return {
        ...state,
        ...data
      };
    case ActionType.QUERY_ASSETS:
      return {
        ...state,
        assets: { ...data },
      };
    default:
      return state;
  }
}

// 约定所有 reducers 都作为 reducers 导出
// 供外部引用 redux 文件后调用 `addReducer(store, reducers);`
export const reducers = { home };

Request

处理与服务端通信,主要功能点如下:

  1. 请求中支持 loading 状态
  2. body 参数结构化
  3. 限制同一接口多次频繁请求
  4. 针对业务错误码或请求网络错误友好提示
  5. Header 中签名/统计/用户标识信息
  6. 打通 nginx、node、service 标识请求唯一的字段
  7. 异常日志记录

Example

// 配置默认 baseURL, 使用相对路径,会自动加上 baseURL 做前缀,使用绝对路径 baseURL 会忽略
// 默认配置 sas 服务为 baseURL,行情接口请求时可直接传绝对地址
Request.request.defaults.baseURL = CONFIG.API_SERVER;
// 超时设置
Request.request.defaults.timeout = 1000 * 60;
// 根据请求配置生成自定义 headers
Request.dynamicHeaders = (config) => { return { sign: sign(config.data) }; };
// 自定义组装 body 的结构
Request.buildBodyStruct = (data) => { return { params: data }; };
// 配置 loading 样式
Request.loading = {
  on: true,
  show() { Loading.show({ content: '加载中', state: 'loading' }); },
  close() { Loading.hide(); },
  fail() { Loading.show({ content: '加载失败', state: 'fail', time: 1500, isHide: true }); }
};
// 业务错误码默认处理
Request.on(Request.ResEvtType.DEFAULT_BIZ_ERR, () => { // 弹框提示错误信息 });
// 业务错误码特殊处理,适用于所有请求的错误码
const AUTH_ERR_CODE = Request.buildBizErrTypeWithCode('123456');
Request.on(AUTH_ERR_CODE, () => { /* 跳转到登录页面 */});
// 适用于特定请求的业务错误码处理
const BIZ_ERR_CODE = Request.buildBizErrTypeWithCode('234567');
Request.once(BIZ_ERR_CODE, () => { // 错误码处理 })
Request.post('/trade', {
  method: 'xxx',
  market, price, bsFlag, secuId, stkCode
}, {
  headers: {
    token: cookies.get('token')
  },
  // 是否展示 loading 提示
  silent: false,
  // preventHandleResError: false
}).then((ret) => {
  // 正常情况处理
}).catch((err) => {
  // 异常处理,一般不需自行处理,除非设置 preventHandleResError 为 true
  // err 可能为业务错误对象(即服务端返回的错误信息)或 Error 的实例(网络错误对象或代码异常对象)
});

// 其他请求方式
// config 具体参数详见 https://github.com/axios/axios#request-config
// 额外增加了 silent, preventHandleResError 两个参数
Request(config);
Request.get(path[, config]);
Request.delete(path[, config]);
Request.head(path[, config]);
Request.options(path[, config]);
Request.patch(path[, data, config]);
Request.post(path[, data, config]);
Request.delete(path[, config]);