Skip to content
This repository has been archived by the owner on May 8, 2020. It is now read-only.

Consider refactoring to use iterators/generators and allow their usage for methods & middleware #19

Open
lutzmor opened this issue Apr 19, 2017 · 0 comments

Comments

@lutzmor
Copy link
Contributor

lutzmor commented Apr 19, 2017

It changes
this

/**
   * Process and persist an entity
   * @param request
   * @param response
   */
  @Route('PUT', '/:id')
  public putOne(request: Request, response: Response): Promise<Response> {

    return request.getPayload()
      .then((data:any) => this.modelStore.hydrate(data))
      .then((model:M) => this.modelStore.validate(model))
      .then((model:M) => this.modelStore.saveOne(model))
      .then((model:M) => response.data(model));
  }

to this:

  /**
   * Process and persist an entity
   * @param request
   * @param response
   */
  @Route('PUT', '/:id')
  public *putOne(request: Request, response: Response): IterableIterator<any> {
    const payload = yield request.getPayload();
    const model = yield this.modelStore.validate(payload);
    yield this.modelStore.validate(payload);
    const savedModel = yield this.modelStore.saveOne(model);
    return yield response.data(savedModel);
  }

dummy POC impl:

class FooController extends ResourceController<any> {

}

let c = new FooController(null, null, null);

const iterator = c.putNOne(null, null);

var value:any;
do {
  var {value, done} = iterator.next(value);

} while(!done);

const response:Response = value;
//not sure yet how to actually resolve the async data out - check if thenable, or thunk?

Pro/Con:

  • 👍 Simpler async expressions
  • 👎 Less familiar syntax for those used to promises
  • 👎 Needs refactor
  • 👍 Exceptions are easier to handle, but having both supported may mean two exception handling strategies
  • 👍 Iterators/Generators are all the rage
  • 👎 Typescript can't declare the final yielded type so every method will have signature *method():IterableIterator<any> unless I'm missing something?

Additional Comment from zakhenry
Holding off on this, as despite being super cute, not being able to strictly define the final yield type is a bit of a deal breaker

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant