Skip to content

Commit

Permalink
Merge pull request #30 from Quramy/docs
Browse files Browse the repository at this point in the history
Docs
  • Loading branch information
Quramy committed Nov 23, 2022
2 parents 5fe76e5 + 42dd00d commit cd44e5f
Show file tree
Hide file tree
Showing 6 changed files with 1,115 additions and 24 deletions.
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx pretty-quick --staged
161 changes: 157 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
# prisma-fabbrica

Factory helper for Prisma.
[![github actions](https://github.com/Quramy/prisma-fabbrica/workflows/build/badge.svg)](https://github.com/Quramy/talt/actions)
[![npm version](https://badge.fury.io/js/@quramy%2Fprisma-fabbrica.svg)](https://badge.fury.io/js/@quramy%2Fprisma-fabbrica)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/Quramy/prisma-fabbrica/main/LICENSE)

Prisma generator for model factories.

## ToC

<!-- toc -->

- [Getting started](#getting-started)
- [Usage of factories](#usage-of-factories)
- [Field default values](#field-default-values)
- [Required relation](#required-relation)
- [Connection helper](#connection-helper)
- [Generator configuration](#generator-configuration)
- [Tips](#tips)
- [Works with jest-prisma](#works-with-jest-prisma)
- [License](#license)

<!-- tocstop -->

## Getting started

Expand Down Expand Up @@ -55,19 +75,152 @@ async function seed() {
await UserFactory.create({ name: "Alice" });
await UserFactory.create({ id: "user002", name: "Bob" });

console.log(await prisma.user.count()); // 3
console.log(await prisma.user.count()); // -> 3
}

seed();
```

Note: The factories uses Prisma client instance passed by `initialize` function.
Note: The factories use Prisma client instance passed by `initialize` function.

## Usage of factories

### Field default values

Factory by defined with `defineUserFactory` automatically fills scalar fields.

For example, the following `User` model has some required field, `id`, `email`, `firstName` and `lastName` .

```graphql
model User {
id Int @id
email String @unique
firstName String
lastName String
middleName String?
createdAt DateTime @default(now())
}
```

```ts
const UserFactory = defineUserFactory();

await UserFactory.create(); // Insert record with auto filled id, email, firstName and lastName values
```

See https://github.com/Quramy/prisma-fabbrica/blob/main/packages/prisma-fabbrica/src/scalar/gen.ts if you want auto filling rule details.

Note: prisma-fabbrica auto filling does not affect fields with `@default()` function.

Default filling rule also can be overwritten.

```ts
const UserFactory = defineUserFactory({
defaultData: async () => {
email: await generateRandomEmailAddress(),
}
})

await UserFactory.create()
```

### Required relation

Sometimes, creating a model requires other model existence. For example, the following model `Post` belongs to other model `User`.

```graphql
model User {
id String @id
name String
posts Post[]
}

model Post {
id String @id
title String
author User @relation(fields: [authorId], references: [id])
authorId String
}
```

You should tell how to connect `author` field when define Post factory.

#### Using related model factory (recommended)

The easiest way is to give `UserFactory` when `definePostFactory` like this:

```ts
const UserFactory = defineUserFactory();

const PostFactory = definePostFactory({
defaultData: {
author: UserFactory,
},
});
```

The above `PostFactory` creates `User` model for each `PostFactory.create()` calling,

#### Manual create or connect

Similar to using `prisma.post.create`, you can also use `connect` / `craete` / `createOrConnect` options.

```ts
const PostFactory = definePostFactory({
defaultData: async () => ({
author: {
connect: {
id: (await prisma.user.findFirst()!).id,
},
// Alternatively, create or createOrConnect options are allowed.
},
}),
});
```

### Connection helper

Required relation rules can be overwritten when `.create` method. `createForConnect` can be used to connect.

```ts
const UserFactory = defineUserFactory();

const PostFactory = definePostFactory({
defaultData: {
author: UserFactory,
},
});

const author = await UserFactory.createForConnect();
await PostFactory.create({ author: { connect: author } });
await PostFactory.create({ author: { connect: author } });

const { posts } = await prisma.user.findUnique({ where: author, include: { posts: true } });
console.log(posts.length); // -> 2
```

## Generator configuration

The following options are available:

```graphql
generator fabbrica {
provider = "prisma-fabbrica"
output = "../src/__generated__/fabbrica"
tsconfig = "../tsconfig.json"
noTranspile = false
}
```

- `output`: Directory path to generate files.
- `tsconfig`: TypeScript configuration file path. prisma-fabbrica uses it's `compilerOptions` when generating `.js` and `.d.ts` files. If missing tsconfig json file, fallback to `--target es2020 --module commonjs`.
- `noTranspile`: If set `true`, this generator only generates raw `.ts` file and stop to transpile to `.js` and `.d.ts` .

## Tips

### Works with jest-prisma

If you use [@quramy/jest-prisma](https://github.com/Quramy/jest-prisma) or [@quramy/jest-prisma-node](https://github.com/Quramy/jest-prisma/packages/jest-prisma-node), you can pass `@quramy/prisma-fabbrica/scripts/jest-prisma` to `setupFilesAfterEnv` in your Jest configuration file.
If you use [@quramy/jest-prisma](https://github.com/Quramy/jest-prisma) or [@quramy/jest-prisma-node](https://github.com/Quramy/jest-prisma/tree/main/packages/jest-prisma-node), you can pass `@quramy/prisma-fabbrica/scripts/jest-prisma` to `setupFilesAfterEnv` in your Jest configuration file.

```js
/* jset.config.mjs */
Expand Down
1 change: 1 addition & 0 deletions examples/example-prj/src/sample.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ describe("factories", () => {
await PostFactory.create({ author: { connect: user } });
await PostFactory.create({ author: { connect: user } });
await PostFactory.create({ author: { connect: user } });
expect(prisma.user.count()).resolves.toBe(1);
const userWithPosts = await prisma.user.findFirst({ where: { name: "quramy" }, include: { posts: true } });
expect(userWithPosts?.posts.length).toBe(3);
});
Expand Down
Loading

0 comments on commit cd44e5f

Please sign in to comment.