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

@alt-point/active-models

v3.2.0

Published

Reactive DTO models with Proxy and more useful classes, decorators, Black-jack and hookers

Downloads

356

Readme

@alt-point/active-models

Пакет с базовыми классами на TS для упрощения работы со структурами данных.

Какие проблемы поможет решить?

  • [x] Реализовать модели данных с реактивными свойствами (ActiveModel);
  • [x] Контролировать целостность структур данных (fillable, hidden, protected);
  • [x] Контролировать тип и целостность данных в каждом конкретном свойстве в рантайме;
  • [x] подписаться на изменения данных в свойствах модели;

Installation

yarn

yarn add @alt-point/active-models

npm

npm install --save @alt-point/active-models

ActiveModel

Класс реализован с использованием Proxy.

Назначение: контроль целостности структуры и типов данных моделей приходящих из внешних источников/подсистем (DTO)

Пример, иллюстрирующий применение

@Decorators

@ActiveField(opts: ActiveFieldDescriptor)

type ActiveFieldDescriptor = object & {
    setter?: Setter<any> // ассессор на установку значения
    getter?: Getter<any> // ацессор на получение значения
    validator?: Validator<any> // валидатор на установку значения
    readonly?: boolean // поле модели будет доступно только на чтение
    hidden?: boolean // поле скрыто из перечисляемых свойств
    fillable?: boolean // поле доступно для установки и изменения
    protected?: boolean // запрещено удалять поле из модели
    attribute?: any // Значение по умолчанию для поля модели в момент создания объекта
    value?: any // алиас для `attribute`
    factory?: typeof ActiveModel | [typeof ActiveModel, () => ActiveModel] // Фабрика (extends ActiveModel) для обработки значения. Массивы так же обрабатывает.
    on?: // листенеры на события модельки, цепляются на конкретное свойство
      beforeSetValue?: ({ target, prop, value, oldValue }) => void // вызовется перед установкой значение 
      afterSetValue?: ({ target, prop, value, oldValue }) => void // сразу после установки значения
      beforeDeletingAttribute?: ({ target, prop }) => void // перед удалением свойства из модели
      nulling?: ({ target, prop, value, oldValue }) => void  // если у свойства было значение и вместо него установили null
    once?: // всё тоже самое, что и в on
}

CallableModel

Базовый класс, реализованный также через Proxy, чтобы можно было обращаться с объектом как с функцией.

Пример использования:


import { CallableModel } from '@alt-point/active-models'

class Notify extends CallableModel {
  // Define
  __call (...args) {
      return this.success(...args)
  }

  success (successMessage) {
     alert(successMessage)
  }

  silent (message) {
    console.log('Silent message:' + message)
  }

}

Дальше можем создать объект класса Notify как плагин в Nuxt.js/Vue.js и использовать:

// плагин
export default (ctx, inject) => {
  ctx.$notify = new Notify()
  inject('notify', new Notify())
}


// в компоненте теперь можно юзать:
this.$notify.silent('Write notice to console!')
this.$notify('Alert!')

TODO:

  • [ ] refactor readonly fields behavior: filling only creating;
  • [ ] add more examples;
  • [ ] tests;
  • [x] TS;
  • [ ] add examples for server (node.js);
  • [x] Translate to english and others languages;

Credits

Alex D. Bubenchikov, [email protected]