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,
};
}
Are you using this plugin? Let us know!