From 5ae4bac295ec30d34f42ab6aa267ab12cce16c23 Mon Sep 17 00:00:00 2001 From: Bret Little Date: Tue, 21 Mar 2023 11:33:40 -0400 Subject: [PATCH] Fix `$relationship.create()` and `$relationship.save()` to accept a single model and an array of models. (#27) --- .changeset/perfect-keys-allow.md | 5 ++++ packages/superflare/src/relations/has-many.ts | 8 ++++-- .../superflare/tests/model/has-many.test.ts | 26 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 .changeset/perfect-keys-allow.md diff --git a/.changeset/perfect-keys-allow.md b/.changeset/perfect-keys-allow.md new file mode 100644 index 00000000..67a334c9 --- /dev/null +++ b/.changeset/perfect-keys-allow.md @@ -0,0 +1,5 @@ +--- +"superflare": patch +--- + +- Fix `$relationship.create()` and `$relationship.save()` to accept a single model and an array of models. diff --git a/packages/superflare/src/relations/has-many.ts b/packages/superflare/src/relations/has-many.ts index cdd0603d..2fe1f1d3 100644 --- a/packages/superflare/src/relations/has-many.ts +++ b/packages/superflare/src/relations/has-many.ts @@ -13,7 +13,9 @@ export class HasMany extends Relation { super(query); } - save(models: any[]) { + save(models: any[] | any) { + models = models instanceof Array ? models : [models]; + return Promise.all( models.map(async (model) => { model[this.foreignKey as keyof Model] = @@ -24,7 +26,9 @@ export class HasMany extends Relation { ); } - create(attributeSets: Record[]) { + create(attributeSets: Record[] | Record) { + attributeSets = attributeSets instanceof Array ? attributeSets : [attributeSets]; + return Promise.all( attributeSets.map(async (attributes) => { const model = new this.query.modelInstance.constructor(attributes); diff --git a/packages/superflare/tests/model/has-many.test.ts b/packages/superflare/tests/model/has-many.test.ts index c63ea0a0..7dfb1b69 100644 --- a/packages/superflare/tests/model/has-many.test.ts +++ b/packages/superflare/tests/model/has-many.test.ts @@ -73,6 +73,19 @@ it("works", async () => { }); it("saves", async () => { + const user = await User.create({ + name: "John Doe", + }); + const posts = await user.$posts().save( + new Post({ + text: "Hello World", + }), + ); + + expect(posts[0].userId).toBe(user.id); +}); + +it("saves array", async () => { const user = await User.create({ name: "John Doe", }); @@ -86,6 +99,19 @@ it("saves", async () => { }); it("creates", async () => { + const user = await User.create({ + name: "John Doe", + }); + const posts = await user.$posts().create( + { + text: "Hello World", + }, + ); + + expect(posts[0].userId).toBe(user.id); +}); + +it("creates array", async () => { const user = await User.create({ name: "John Doe", });