factory-girl icon indicating copy to clipboard operation
factory-girl copied to clipboard

Invalid params when callback afterBuild and afterCreate in case create/buildMany

Open Duy-Tan-Nguyen opened this issue 5 years ago • 0 comments

Dear wonderful library author and maintainers,

As I understand, these 2 methods in Factory.js file: afterBuild and afterCreate are called with the following params: model, modelAttrs, modelBuildOptions.

But when using buildMany / createMany, the modelAttrs and modelBuildOptions are passed by attrsArray, buildOptionsArray instead of attrsArray[index] and buildOptionsArray[index]. I propose the fix is:

async buildMany(adapter, num, attrsArray = [], buildOptionsArray = [], buildCallbacks = true) {
    const attrs = await this.attrsMany(num, attrsArray, buildOptionsArray);
    const models = attrs.map(attr => adapter.build(this.Model, attr));
    return Promise.all(models).then(builtModels =>
      this.options.afterBuild && buildCallbacks
        ? Promise.all(
            builtModels.map((builtModel, index) =>
              this.options.afterBuild(builtModel, attrsArray[index], buildOptionsArray[index]),
            ),
          )
        : builtModels,
    );
  }

  async createMany(adapter, num, attrsArray = [], buildOptionsArray = []) {
    if (Array.isArray(num)) {
      buildOptionsArray = attrsArray;
      attrsArray = num;
      num = attrsArray.length;
    }
    const models = await this.buildMany(adapter, num, attrsArray, buildOptionsArray);
    const savedModels = models.map(model => adapter.save(model, this.Model));
    return Promise.all(savedModels).then(createdModels =>
      this.options.afterCreate
        ? Promise.all(
            createdModels.map((createdModel, index) =>
              this.options.afterCreate(createdModel, attrsArray[index], buildOptionsArray[index]),
            ),
          )
        : createdModels,
    );
  }

Could you please take a look and fix the issue? Thanks a lot!

Duy-Tan-Nguyen avatar Oct 14 '19 04:10 Duy-Tan-Nguyen