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

@monsterooo/model

v1.0.9

Published

> TODO: description

Downloads

1

Readme


title: Model sidemenu: false nav: title: Model path: /model order: 5

Model

dva 扩展

插件

dva 扩展模块,在 dva 的插件基础上扩展了 model 插件功能,其 hooks 包含两部分:

  • model 注册 hook(state、subscription、effect、reducer), app 注册 model 的时候会调用插件的 hook 并返回新的对象。
  • dva 官方 hook,具体请参考官方插件指南

现有的功能都是在插件的基础上实现的,默认集成如下插件:

  • update
  • put
  • listen
  • loading
  • select
  • request

下面分别介绍各个插件提供的功能。

update

新增 update effect, 方便进行 state 数据更新操作,避免为每次 state 更改设置 reducer. update 插件会给所有 model 添加 updateState reducer

{
  reducer: {
    updateState() {
      ...
    }
  }
}

使用示例:

//model
export default {
  namespace: 'user',
  effects: {
    *fetchUsers({ payload }, { call, update }) {
      const users = yield call(services.user.getList);
      yield update({ users });
    },
  },
};

put

简化 put effect 的书写,put 仍然保留 dva 官方 resolve 扩展。参考如下示例:

// 原始put
yield put({ type: 'updateUsers', payload: { users }});
// 简化之后
yield put('updateUsers', { users });


yield put.resolve({ type: 'other/fetch'})
// or
yield put.resolve('other/fetch')

listen

为方便对浏览器 path 的监听,在 model 的 subscriptions 配置函数中,添加扩展方法listen自动处理路由监听以及参数。

listen函数参数如下:

  • pathReg 需要监听的 pathName,它支持被 pathToRegexp 解析
  • action action 既可以是 redux action,也可以是一个回调函数如果action是函数,调用时,将传入{ ...location, query, params, paramsObj }作为其参数 query 为普通对象,用法:const { sid } = query params 为类数组,支持的用法有:const [id] = params 或 const { id } = params paramsObj 为普通对象,和 params 的数据一样,只是数据结构不同,所以用法只有:const { id } = paramsObj

listen 函数也支持同时对多个 pathname 的监听,传入的参数需要为{pathReg: action}健值对的对象 listen 函数可以传入两个回调,分别表示进入 path 时和离开 path 时

import model from 'configs/model';
import qs from 'qs';

export default {
  namespace: 'user',

  subscriptions: {
    setup({ dispatch, listen }) {
      // action 为 redux action
      listen('/user/list', { type: 'fetchUsers'});

      // action 为回调函数1
      listen('/user?sid=1', ({ query }) => dispatch({ type: 'fetchUser', payload: query }));

      // action 为回调函数2
      listen('/user/:userId/project/:proojectId', () => dispatch({ type: 'fetchUsers' }));

      // 支持对多个 path 的监听
      listen({
        '/user/list': ({ query, params }) => {},
        '/user/query': ({ query, params }) => {},
      });

      // 在之前的用法之上,传入第三个参数表示离开 path 的回调
      listen('/user/list', { type: 'fetchUsers'}, { type: 'clearUsers'});

      // 同上也支持对多个 path 的监听
      listen({
        '/user/list': [({ query, params }) => { console.log('enter'); }, ({ query, params }) => { console.log('leave'); }],
        '/user/query': [({ query, params }) => { console.log('enter'); }, ({ query, params }) => { console.log('leave'); }],
      });
    },
  },
  effects: {
    * fetchUsers({ payload }, { select }) {
      const { userId, proojectId } = yield select('user');
      ...
    },
  },
})

select

简化 select effect 的使用, 提供以下三种用户:

const { list } = yield select(({ user }) => user);
const { list } = yield select('user');
const [user, department] = yield select(['user', 'department']);

loading state

主要为了方便对 loading 状态进行处理。loading 插件灵感来源于dva-loading 插件。在设计上与官方插件稍有不同,官方插件 loading 状态使用全局的 model 处理,而 loading 插件会将各 model 的 loading 状态,保存在当前 namespace 的 state 中。

使用 loading 插件后,会给所有 model 添加 loading state 以及 updateLoading reducer, 请注意对应的命名,以避免被覆盖.

state: {
  loading: {
    global: false, // model级别loading
  }
},
reducer: {
  updateLoading() {
    ...
  }
}

loading 插件会自动处理 effect 级别 loading,在 model effect 执行前后自动更新 loading 中对应 effetName 的状态,并更新 loading.global, 如果当前 model 的 loading 存在为 true 的属性,则将 loading.global 设置为 true。使用方式如下:

// model
{
  namespace: 'book'
  effects: {
    * fetch() {
      yield call(..)
    }
  }
}


// 执行fetch前state
{
  loading: {
    fetch: true,
    global: true,
  }
}

// 执行fetch后state
{
  loading: {
    fetch: false,
    global: ...
  }
}


// page
connect(({ book}) => {
  // 这里可以聚合loading属性
  return book;
})(Page)

function (props) {
  const onSave = () => {
    await props.save();
    message.warn('保存成功')
  }
  return <Spin loading={props.loading.save}></Spin><div onClick={onSave}>保存</div>
}

request

常用于列表操作,将操作请求、成功提示、刷新列表封装在一起。

function* request(action, payload, options = {}) {
  const { successInfo = '操作成功', effectName = 'getList' } = options;

  try {
    const result = yield call(action, payload);
    const { search } = yield select(namespace);
    yield put({ type: effectName, payload: search });

    successInfo && message.success(successInfo);
    return result;
  } catch (e) {
    return Promise.reject(e);
  }
}

API

createModel

| 参数 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | | pagePath | 页面路径,配置后自动监听页面并发起 getList 请求 | string | - | | handleParams | 参数处理函数,发起请求默认会带上路径参数 | Function(params) | - | | queries | 设置后会请求会带上 query 上的参数 | array | string | - | | getContent | 返回值处理函数 | Function(content) | - | | apiPath | 请求地址,配置后会自动生成 getList effect | Function | - | | effects.beforeList | getList 请求前回调 | Function | - | | effects.afterList | getList 请求后回调 | Function | - |

connectModel

对 dva connect 的二次封装, 自动将 model 中的 stateeffectsreducers 注入到组件中

| 参数 | 说明 | 类型 | 默认值 | | ------- | --------------- | ------ | ------ | | ...keys | model namespace | string | - |