Skip to content

zhouzi/graphql-codegen-factories

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
April 17, 2022 11:44
April 12, 2022 18:59
January 20, 2023 16:28
January 20, 2023 19:29
March 6, 2022 12:13
April 17, 2022 11:44
January 20, 2023 19:29
June 26, 2020 14:40
December 31, 2022 17:05

graphql-codegen-factories

graphql-codegen-factories is a plugin for GraphQL Code Generator that generates factories from a GraphQL schema and operations. The factories can then be used to mock data, e.g for testing or seeding a database.

For example, given this GraphQL schema:

type User {
  id: ID!
  username: String!
}

The following factory will be generated:

export type User = /* generated by @graphql-codegen/typescript */;

export function createUserMock(props: Partial<User> = {}): User {
  return {
    __typename: "User",
    id: "",
    username: "",
    ...props,
  };
}

It is also possible to generate factories from an operation, for example:

query GetUser {
  user {
    id
    username
  }
}

Will result in the following factories:

export type GetUserQuery = /* generated by @graphql-codegen/typescript-operations */;

export function createGetUserQueryMock(props: Partial<GetUserQuery> = {}): GetUserQuery {
  return {
    __typename: "Query",
    user: createGetUserQueryMock_user({}),
    ...props,
  };
}

export function createGetUserQueryMock_user(props: Partial<GetUserQuery["user"]> = {}): GetUserQuery["user"] {
  return {
    __typename: "User",
    id: "",
    username: "",
    ...props,
  };
}

You can also use a fake data generator to generate realistic factories such as:

import { faker } from "@faker-js/faker";

export function createUserMock(props: Partial<User> = {}): User {
  return {
    __typename: "User",
    id: faker.random.alphaNumeric(16),
    username: faker.lorem.word(),
    ...props,
  };
}

Showcase

Are you using this plugin? Let us know!

Contributors