Skip to content

Commit

Permalink
Fix $relationship.create() and $relationship.save() to accept a s…
Browse files Browse the repository at this point in the history
…ingle model and an array of models. (#27)
  • Loading branch information
blittle committed Mar 21, 2023
1 parent 209c4b3 commit 5ae4bac
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/perfect-keys-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"superflare": patch
---

- Fix `$relationship.create()` and `$relationship.save()` to accept a single model and an array of models.
8 changes: 6 additions & 2 deletions packages/superflare/src/relations/has-many.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] =
Expand All @@ -24,7 +26,9 @@ export class HasMany extends Relation {
);
}

create(attributeSets: Record<string, any>[]) {
create(attributeSets: Record<string, any>[] | Record<string, any>) {
attributeSets = attributeSets instanceof Array ? attributeSets : [attributeSets];

return Promise.all(
attributeSets.map(async (attributes) => {
const model = new this.query.modelInstance.constructor(attributes);
Expand Down
26 changes: 26 additions & 0 deletions packages/superflare/tests/model/has-many.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
});
Expand All @@ -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",
});
Expand Down

0 comments on commit 5ae4bac

Please sign in to comment.