zerothstack / zeroth

Core library of the Zeroth Stack
MIT License
36 stars 2 forks source link

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

Open lutzmor opened 7 years ago

lutzmor commented 7 years ago

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:

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