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

nest-monk

v1.2.0

Published

A thin wrapping layer around the monk package for clean NestJS dependency injection.

Downloads

8

Readme

Features

  • A simple dependency injection model with MonkModule.forRoot(), MonkModule.forRootAsync() and MonkModule.forFeatures().
  • @InjectCollection(MyModel) decorator for injecting Monk collection instances.
  • Simple auto-generated CRUD repositories for models, injectable by @InjectRepository(MyModel).
  • Built-in TypeScript class transformations using the class-transformer package and monk middleware.

How To Use

Install

npm install --save nest-monk monk

Importing

MonkModule.forRoot()

MonkModule.forRoot() is the simplest way to import the Monk dependencies and uses static values.

// app.module.ts
@Module({
  imports: [
    MonkModule.forRoot({
      database: 'mongodb://127.0.0.1:27017',
      options: {
        ssl: true,
      }
    }),
  ],
})
class AppRootModule {}

database

database is the connection string to the Mongo server and database.

options

options are the monk options to be passed into the instantiation. See monk Manager documentation for more details.

MonkModule.forRootAsync()

MonkModule.forRootAsync() allows for a FactoryProvider or ValueProvider dependency declaration to import your module. Note that ExistingProvider and ClassProvider are not yet supported.

// app.module.ts
@Module({
  imports: [
    MonkModule.forRootAsync({
      database: {
        useFactory: async (ms: MongoServer) => {
          const server = await ms.startServer();
          return await server.getConnectionString();
        },
        inject: [MongoServer],
        imports: [MongoServerModule],
      },
    }),
  ],
})
class AppRootModule {}

Registering Model Collections

Models

Models are the shape of the data in your collection. If you would like to let nest-monk use simple defaults, you simply can pass a class to the collection registration (see below), but the @Model() decorator can be used to provide optional overrides to collection settings.

Without decorator

// user.model.ts

// default collection name is "users". no indexes will be configured.
class User {
  _id: string;
  name: string;
}

With decorator

// user.model.ts

@Model({
  collectionName: 'app_users',
  collectionOptions: o => o.createIndex('name', { unique: true }),
})
class User {
  _id: string;
  name: string;
}
collectionName

This is the name of the collection stored in the Mongo database.

collectionOptions

This will be executed against the collection. This is where modifications to the collection should go, i.e. creation of indexes.

forRoot registration

Models can be registered at the root level in the collections array by passing the type symbol to the array. Note, if you register models here, do not register them in feature modules as unexpected behavior is likely.

// app.module.ts

@Module({
  imports: [
    MonkModule.forRoot({
      database: 'mongodb://127.0.0.1:27017',
      collections: [User],
    }),
  ],
})
class AppRootModule {}

forFeatures registration

Models can be registered at submodule levels using the MonkModule.forFeatures() method. Similar to the root-level registration, simply pass an array of Model types.

// user.model.ts
@Model()
class User {
  _id: string;
  name: string;
}

// user.module.ts
@Module({
  imports: [MonkModule.forFeatures([User])],
})
class UserModule {}

Collection injection

Collections can be injected using the @InjectCollection() decorator. Collections are a monk construct that nest-monk exposes through dependency injection.

@Injectable()
class UserService {
  constructor(
    @InjectCollection(User) readonly usersCollection: ICollection<User>,
  ) {}

  async getAll() {
    return await this.usersCollection.find();
  }
}

Repository injection

Repositories can be injected using the @InjectRepository() decorator. The repositories are created by nest-monk and are a simple CRUD interface handy for quickly creating REST controllers.

  • getById(id: string) - Retrieves data by the default mongo _id property.
  • list(query: string | Object) - Retrieves data given the mongo query. Leave empty to retrieve all.
  • add(model: T) - Saves the given model to the database.
  • delete(id: string) - Deletes the given data from the database.
  • edit(id: string, model: T, setProperties?: (keyof T)[]) - Updates the data for the given ID. Use setProperties to define specific properties to set, or leave undefined to set all properties.
@Controller()
class UserController {
  constructor(
    @InjectRepository(User) readonly usersRepository: Repository<User>,
  ) {}

  @Get(':id')
  async getById(id: string) {
    return await this.usersRepository.getById(id);
  }
}

Stay In Touch

License

nest-monk is MIT licensed.

Contributing

Nest-monk is released through semantic-release. Effectively this means that versioning is based off commit messages. Please review angular-changelog-convention and commit under that format. Otherwise semantic-release won't detect commits which should version the library.