npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zainundin/mongoose-factory

v1.1.1

Published

A utility for generating and creating instances of Mongoose models with ease.

Downloads

29

Readme

@zainundin/mongoose-factory

@zainundin/mongoose-factory is a utility for generating and creating instances of Mongoose models with ease.

Installation

You can install @zainundin/mongoose-factory via npm:

npm install @zainundin/mongoose-factory

Usage

To use @zainundin/mongoose-factory, you need to create a subclass of the BaseFactory class and implement the definition() method to define the structure of the data you want to generate.

Example Usage with Faker

Here's an example of how to use @zainundin/mongoose-factory with Faker for generating fake data and applying state mutations with the withState() method:

import { Model } from 'mongoose';
import BaseFactory from '@zainundin/mongoose-factory';
import { faker } from '@faker-js/faker';

// Define your Mongoose model
const YourModel = Model(/* Your Mongoose model schema */);

// Create a subclass of BaseFactory for your model
class YourModelFactory extends BaseFactory {
    constructor() {
        super(YourModel);
    }

    // Implement the abstract definition method
    async definition() {
        // Define the structure of your data here
        return {
            name: faker.person.fullname(),
            email: faker.internet.email(),
            age: faker.number.int({max: 120, min: 10}),
            status: faker.helpers.enumValue(['active', 'inactive']),
            isAdmin: faker.datatype.boolean(),
            createdAt: faker.date.recent()
        };
    }

    // Add a new method to apply state mutations
    async isAdmin() {
        await this.withState({isAdmin: true});
        return this;
    }
}

// Create an instance of YourModelFactory
const yourModelFactory = new YourModelFactory();

Generate a Single Instance of Your Model

You can generate a single instance of your model without any mutations:

// Generate a single instance of your model
const instance = await yourModelFactory.make();
console.log(instance); // Output: The generated instance of your model

Generate Instances of Your Model with Count

You can generate multiple instances of your model with the specified count:

// Generate multiple instances of your model with count
const instances = await yourModelFactory.count(5).make();
console.log(instances); // Output: An array of 5 generated instances of your model

Generate a Single Instance of Your Model with State Mutations (Partial Object)

You can generate a single instance of your model with specific state mutations using the withState() method:

// Generate a single instance of your model with state mutations (partial object)
const instanceWithStatePartial = await yourModelFactory
    .withState({ status: 'active', isAdmin: true })
    .make();
console.log(instanceWithStatePartial); // Output: The generated instance of your model with applied state mutations

Generate an Instance of Your Model with Specific State Using Custom Method

You can generate a single instance of your model with specific state applied through a custom method:

// Generate a single instance of your model with specific state using a custom method
const instanceWithAdminState = await yourModelFactory
    .isAdmin()
    .make();
console.log(instanceWithAdminState); // Output: The generated instance of your model with isAdmin set to true

Generate a Single Instance of Your Model with State Mutations (Function Returning Recent Faker Date)

You can also generate a single instance of your model with state mutations using a function returning a recent Faker date:

// Generate a single instance of your model with state mutations (function returning recent Faker date)
const instanceWithStateFunction = await yourModelFactory
    .withState(() => ({ createdAt: faker.date.recent() }))
    .make();
console.log(instanceWithStateFunction); // Output: The generated instance of your model with applied state mutations

In this updated example:

  • We provide separate blocks for generating a single instance of your model, generating multiple instances of your model with count, generating a single instance of your model with state mutations (partial object), generating a single instance of your model with specific state using a custom method, and generating a single instance of your model with state mutations (function returning recent Faker date).
  • The example usage with Faker and the API section remain unchanged.

You may need to adjust the import statements, variable names, and method implementations according to your project's specific details.

API

BaseFactory<T>

Methods

  • count(quantity: number): this: Sets the quantity of instances to generate.
  • withState(state: Partial<T> | (() => Promise<Partial<T>>)): this: Adds state mutations to modify the generated data.
  • make(): Promise<T | T[]>: Generates instances without persisting them.
  • create(): Promise<T | T[]>: Generates and persists instances to the database.

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License. See the LICENSE file for details.