connor4312 / cockatiel

🐦 A resilience and fault-handling library. Supports Backoffs, Retries, Circuit Breakers, Timeouts, Bulkhead Isolation, and Fallbacks.
MIT License
1.59k stars 50 forks source link

Is there a plan making a decorator for TS? #8

Closed yuu2lee4 closed 4 years ago

yuu2lee4 commented 4 years ago

Like https://github.com/DavideCarvalho/hystrixjsDecorator.

connor4312 commented 4 years ago

Good idea. I can do this tonight, also happy to take PRs.

connor4312 commented 4 years ago

Added this for 0.1.3:

Policy.use(policy)

A decorator that can be used to wrap class methods and apply the given policy to them. It also adds the last argument normally given in Policy.execute as the last argument in the function call. For example:

import { Policy } from 'cockatiel';

const retry = Policy.handleAll()
  .retry()
  .attempts(3);

class Database {
  @Policy.use(retry)
  public getUserInfo(userId, context) {
    console.log('Retry attempt number', context.attempt);
    // implementation here
  }
}

const db = new Database();
db.getUserInfo(3).then(info => console.log('User 3 info:', info));

Note that it will force the return type to be a Promise, since that's what policies return.