Skip to content
This repository was archived by the owner on May 8, 2020. It is now read-only.
This repository was 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

@lutzmor

Description

@lutzmor

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions