Skip to main content

Usage with faker-js

info

faker-js is a popular library used to "generate realistic data and not obvious fake data"

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

const fakerUserGenerator = () => ({
id: faker.string.uuid(),
first_name: faker.person.firstName(),
last_name: faker.person.lastName(),
company: faker.company.name()
});

const { generate } = mocq({
users: {
generator: fakerUserGenerator,
count: 100,
}
});

const { data: { users } } = generate();

Sample Resolved Data

users:

[
{
id: "c0d180fa-6933-4184-a503-dd96fb0b565a",
first_name: "Bonita",
last_name: "Orn",
company: "Lubowitz and Sons"
},
{
id: "f72f7c86-569d-4f35-bc66-b4df6b8b1a5e",
first_name: "Clara",
last_name: "Dickinson",
company: "Kihn LLC"
},
{
id: "6232f606-56ba-4f2e-8e2d-367685731379",
first_name: "Bell",
last_name: "Douglas",
company: "Ledner LLC"
},
// ... 97 more entries
]
warning

when generating unique fields, consider creating a string literal with the index when not using faker.string.uuid as faker will duplicate random values in large enough data sets

const fakerCompanyGenerator = (i) => ({
company: `${faker.company.name()} (${i})`
});
tip

faker has many useful helper functions including faker.helpers.arrayElement which grabs a random value from an array, it works great as a connection function if the desired result is that the data is simply connected in some way

const { generate } = mocq({
users: {
generator: fakerUserGenerator,
count: 100,
connections: {
companies: (data)=>({ company: faker.helpers.arrayElement(data).id })
}
},
companies: {
generator: fakerCompanyGenerator,
count: 25
}
});

const { data: { users, companies } } = generate();