thoughtbot / fishery

A library for setting up JavaScript objects as test data
MIT License
876 stars 36 forks source link

Update fishery to support bulk operations #66

Closed RiyaAggarwal123 closed 2 years ago

RiyaAggarwal123 commented 3 years ago

We are using fishery to create test data on remote servers via APIs, and we are using createList(), which iterates on each object and calls onCreate() method (which hits API) for each object. Making an API call for each object is inefficient, so we added a bulk-create hook to perform bulk-operations.

Now we are providing support for bulk create, in which it calls theonBulkCreate()method (which hits create api only one time for all the objects) if bulkCreate flag passes true to createList().

For example: bulkUserFactory.createList(2, { name: 'susan' }, { bulkCreate: true });

sedge commented 3 years ago

@stevehanson This is an excellent feature addition and looks really well developed. What are the chances we can see this merged?

stevehanson commented 3 years ago

Thank you for this contribution. I am still considering if this is something we would include in Fishery.

In the meantime if anyone else is needing this functionality, you could always define your own factory that supports this and use it in your project, something like:

abstract class BulkFactory<T, I = any> extends Factory<T, I, T> {
  abstract onBulkCreate(_list: T[]): Promise<T[]>;

  bulkCreate(
    number: number,
    params: DeepPartial<T> = {},
    options: BuildOptions<T, I> = {},
  ): Promise<T[]> {
    const list = this.buildList(number, params, options);
    return this.onBulkCreate(list);
  }
}

class UserFactory extends BulkFactory<User> {
  onBulkCreate(list: User[]) {
    return Promise.resolve(list);
  }
}

const users = await userFactory.bulkCreate(2, { name: 'susan' });
expect(users.length).toEqual(2);
expect(users[0].name).toEqual('susan');
stevehanson commented 2 years ago

I'm going to close this as it is not something we are interested in adding to the library at this time. I recommend using the supplied code from my comment above to create your own implementation if needed.