Skip to content

Commit

Permalink
Merge pull request #40 from Quramy/build_create_input_docs
Browse files Browse the repository at this point in the history
docs: Write about buildCreateInput method
  • Loading branch information
Quramy committed Nov 24, 2022
2 parents c3c1f18 + 567c7f1 commit 596b65a
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Prisma generator for model factories.
- [Field default values](#field-default-values)
- [Required relation](#required-relation)
- [Connection helper](#connection-helper)
- [Build input data only](#build-input-data-only)
- [Generator configuration](#generator-configuration)
- [Tips](#tips)
- [Works with jest-prisma](#works-with-jest-prisma)
Expand Down Expand Up @@ -199,6 +200,44 @@ const { posts } = await prisma.user.findUnique({ where: author, include: { posts
console.log(posts.length); // -> 2
```

### Build input data only

`.buildCreateInput` method in factories provides data set to create the model, but never insert.

```ts
await UserFactory.create();

// The above code is equivalent to the bellow:
const data = await UserFactory.buildCreateInput();
await prisma.user.create({ data });
```

For example, you can use `.buildCreateInput` method in other model's factory definition:

```ts
const UserFactory = defineUserFactory();

const PostFactory = definePostFactory({
defaultData: async () => ({
author: {
connectOrCreate: {
where: {
id: "user001",
},
create: await UserFactory.buildCreateInput({
id: "user001",
}),
},
},
}),
});

await PostFactory.create();
await PostFactory.create();

console.log(await prisma.user.count()); // -> 1
```

## Generator configuration

The following options are available:
Expand Down
29 changes: 29 additions & 0 deletions examples/example-prj/src/sample.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,21 @@ const PostFactory = definePostFactory({
},
});

const PostFactoryAlt = definePostFactory({
defaultData: async () => ({
author: {
connectOrCreate: {
where: {
id: "user001",
},
create: await UserFactory.buildCreateInput({
id: "user001",
}),
},
},
}),
});

describe("factories", () => {
describe("UserFactory", () => {
it("creates records without input parameters", async () => {
Expand Down Expand Up @@ -43,4 +58,18 @@ describe("factories", () => {
expect(userWithPosts?.posts.length).toBe(3);
});
});

describe("PostFactoryAlt", () => {
it("creates post record", async () => {
await PostFactoryAlt.create();
await expect(prisma.user.count()).resolves.toBe(1);
});

it("creates related user at most one", async () => {
await PostFactoryAlt.create();
await PostFactoryAlt.create();
await PostFactoryAlt.create();
await expect(prisma.user.count()).resolves.toBe(1);
});
});
});

0 comments on commit 596b65a

Please sign in to comment.