Git Product home page Git Product logo

kaop's Introduction

kaop

Image travis version Coverage Status dependencies dev-dependencies downloads Known Vulnerabilities

Lightweight, solid, framework agnostic and easy to use library which provides reflection features to deal with Cross Cutting Concerns and improve modularity in your code.

Try it!

Clone the repo: git clone https://github.com/k1r0s/kaop.git

Run showcase: node showcase.js

Run tests: npm test

Features, from bottom to top.

  • ES6 class alternative
  • Inheritance
  • Composition
  • Method Overriding
  • Dependency Injection
  • AOP Extensions

Get started

npm install kaop --save
import { extend } from 'kaop'

// Array.prototype.includes() polyfill
const MyArray = extend(Array, {
  includes(value) {
    return this.indexOf(value) > -1;
  }
});

const arr = new MyArray(1, 2, 3, 4);

arr.includes(2); // true
arr.includes(5); // false

Easy, right? lets try something else.

Say that for calculating John Doe's age we have to waste a lot of resources so we want to apply memoization to one method.

// create a spy function
const methodSpy = jest.fn();

const Person = createClass({
  constructor(name, yearBorn) {
    this.name = name;
    this.age = new Date(yearBorn, 1, 1);
  },

  // note that `sayHello` always calls `veryHeavyCalculation`
  veryHeavyCalculation: [Memoize.read, function() {
      // call spy function
      methodSpy();
      const today = new Date();
      return today.getFullYear() - this.age.getFullYear();
  }, Memoize.write],

  sayHello(){
    return `hello, I'm ${this.name}, and I'm ${this.veryHeavyCalculation()} years old`;
  }
})

// ... test it
it("cache advices should avoid 'veryHeavyCalculation' to be called more than once", () => {
  const personInstance = new Person("John Doe", 1990);
  personInstance.sayHello();
  personInstance.sayHello();
  personInstance.sayHello();
  expect(methodSpy).toHaveBeenCalledTimes(1);
});
// we're creating a group of advices which provides memoization
const Memoize = (function() {
  const CACHE_KEY = "#CACHE";
  return {
    read: reflect.advice(meta => {
      if(!meta.scope[CACHE_KEY]) meta.scope[CACHE_KEY] = {};

      if(meta.scope[CACHE_KEY][meta.key]) {
        meta.result = meta.scope[CACHE_KEY][meta.key];
        meta.break();
      }
    }),
    write: reflect.advice(meta => {
      meta.scope[CACHE_KEY][meta.key] = meta.result;
    })
  }
})();

O_O what are advices?

Advices are pieces of code that can be plugged in several places within OOP paradigm like 'beforeMethod', 'afterInstance'.. etc. Advices are used to change, extend, modify the behavior of methods and constructors non-invasively.

If you're looking for better experience using advices and vanilla ES6 classes you should check kaop-ts which has a nicer look with ES7 Decorators.

But this library isn't only about Advices right?

This library tries to provide an alternative to ES6 class constructors which can be nicer in some way but do not allow reflection (it seems that ES7 Decorators are the way to go but they're still experimental) compared to createClass prototyping shell which provides a nice interface to put pieces of code that allows declarative Inversion of Control.

Once you have reflection...

Building Dependency Injection system is trivial. For example:

import { createClass, inject, provider } from 'kaop'


// having the following service
const Storage = createClass({
  constructor: function() {
    this.store = {};
  },
  get: function(key){
    return this.store[key];
  },
  set: function(key, val){
    return this.store[key] = val;
  }
});

// you declare a singleton provider (you can use a factory for multiple instances)
const StorageProvider = provider.singleton(Storage);

// and then you inject it in several classes
const Model1 = createClass({
  constructor: [inject.args(StorageProvider), function(_storageInstance) {
    this.storage = _storageInstance;
  }]
});

const Model2 = createClass({
  constructor: [inject.args(StorageProvider), function(_storageInstance) {
    this.storage = _storageInstance;
  }]
});

const m1 = new Model1;
const m2 = new Model2;

m1.storage instanceof Storage // true
m2.storage instanceof Storage // true

// and they are the same instance coz `StorageProvider` returns a single instance `singleton`

TODO

Way more documentation about Aspect Oriented, Dependency Injection, Composition, Asynchronous Advices, etc.

Tests are the most useful documentation nowadays, that should change soon.

Similar resources

kaop's People

Contributors

alexjoverm avatar alvyuste avatar k1r0s avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

kaop's Issues

push & commit feature

shortcut or alias of

  meta.args.push(session);
  meta.commit();

something like:

  meta.commit(session); // if commit receives any argument it appends to meta.args

Most of times, advices define actions that must fetch something or perform some action and then, push that result to the main arguments of target method. It would be handy to have a way to do so in one instruction

Compatibility with ES6 classes

const { createClass } = require("kaop");

const Test = createClass({
  constructor(_salute) {
    this.salute = _salute
  }
})

class SuperTest extends Test {
  constructor() {
    super("Hi")
  }

  printSalute() {
    console.log(this.salute)
  }
}

let t = new SuperTest // TypeError: Class constructor SuperTest cannot be invoked without 'new'

t.printSalute();

hooks "first" and "last"

this.point(function(){  ...  });
this.first(function(){  ...  });
this.before(function(){  ...  });
this.after(function(){  ...  });
this.last(function(){  ...  });

Async aspects share the same Promise instance across calls

The current implementation causes async aspects to share the same Promise instance across calls.

On subsequent calls, this will cause the decorated method and its after execution aspects to run outside of the chain starting in the already resolved Promise of the previous calls.

To illustrate the bug, I've created this test in the promise-advice-method.spec.js spec:

it("promise should not already be resolved on repeated calls", () => {
  return instance.do1().then(() => {
    var beforeTimestamp = new Date();

    return instance.do1().then(() => {
      var now = new Date();
      var delta = now.getTime() - beforeTimestamp.getTime();

      expect(delta).toBeGreaterThanOrEqual(10);
    });
  });
})

My proposed fix is to instantiate the Promise, when needed, within the proxy function:

function createProxyFn(target, key, functionStack, customInvoke) {
  return createProxy(target, key, functionStack, customInvoke);
}

function createProxy(target, key, functionStack, customInvoke) {
  return function() {
    var prom, resolve, reject;
    var shouldReturnPromise = key !== "constructor" && functionStack.some(function (_) { return utils.isAsync(_); });

    if(shouldReturnPromise) {
      prom = new Promise(function (_resolve, _reject) {
        resolve = _resolve;
        reject = _reject;
      });
    }

    let adviceIndex = -1;
    ...

ESM export is problematic

Hi, in dist/kaop.esm.js export looks like

var src = {
  createClass: main.createClass,
  ...
};
export default src;

and that makes import { extend } from 'kaop' invalid - it's not possible to destruct object in import like this, you can only do import kaop from 'kaop'; kaop.extend ...

This breaks kaop-ts bundled with esm aware bundler like parcel or browser supportig esm modules.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.