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

mongoose-safe-query

v0.2.2

Published

A mongoose plugin that verifies the fields in a query

Downloads

3,617

Readme

Mongoose Safe Query

build npm version

A mongoose plugin that verifies the fields in a query to ensure that:

  • All fields exist in mongoose schema.
  • The query has sufficient index coverage.

When there is any violation, you can configure the plugin to run arbitrary code, or throw a customizable message.

Installation

npm install mongoose-safe-query

Usage

Apply the plugin to all schemas:

import mongoose from 'mongoose';
import { SafeQuery } from 'mongoose-safe-query';

const safeQuery = new SafeQuery();
const safeQueryPlugin = safeQuery.getPlugin();

mongoose.plugin(safeQueryPlugin);

// Define schemas afterwards

Apply the plugin to specific schemas:

import mongoose from 'mongoose';
import { SafeQuery } from 'mongoose-safe-query';

const safeQuery = new SafeQuery();
const safeQueryPlugin = safeQuery.getPlugin();

const schema = new mongoose.Schema({ /* schema definition */ });

schema.plugin(safeQueryPlugin);

Usually you have multiple schemas. You can create the safeQuery instance and safeQueryPlugin in a separate file, and share it with all the schemas. See Notes below to details.

Configurations

When creating a SafeQuery instance, you can customize the plugin as follows.

Example

const safeQuery = new SafeQuery()
  // Always warn
  .setWarnCondition(true)
  // Only throw in non-production environment
  .setThrowCondition(() => process.env.NODE_ENV !== 'production')
  .setFieldCheckHandler({
    warnAction: (query: ViolatingQuery) => {
      // Log to your logging framework
    },
    throwMessage: (query: ViolatingQuery) => {
      return `Query fields do not exist in ${query.modelName}: ` +
        query.violatingFields.join(', ');
    },
  })
  .setIndexCheckHandler({
    // Query requires at least 25% index coverage
    minCoverage: 0.25,
    warnAction: (query: ViolatingQuery) => {
      // Log to your logging framework
    },
    throwMessage: (query: ViolatingQuery) => {
      return `Query has insufficient index coverage in ${query.modelName}: ` +
        query.violatingFields.join(', ');
    },
  });

Overall

| Option | Type | Setter | Definition | | ---- | ---- | ---- | ---- | | shouldWarn | () => boolean | setWarnCondition | Whether a warning action should be run if there is any violation. Default to always return true. | | shouldThrow | () => boolean | setThrowCondition | Whether an exception should be thrown if there is any violation. Default to always return false. | | checkField | object | setFieldCheckHandler | See Field Existence Config. | | checkIndex | object | setIndexCheckHandler | See Index Coverage Config. |

  • For convenience, you can pass in a boolean constant to setWarnCondition and setThrowCondition if no dynamic evaluation is needed.

Field Existence Config

  • This config determines what to do if a query has fields that do not exist in the schema.
  • Setter: setFieldCheckHandler.

| Option | Type | Default | Definition | | ---- | ---- | ---- | ---- | | warnAction | (query: ViolatingQuery) => void | Log a warning message to console. | Given a violation query, define the warning action to run. | | throwMessage | (query: ViolatingQuery) => string | undefined | Given a violation query, return a message. This message will be wrapped in InvalidField error and thrown. |

  • The plugin will only run the warning action if shouldWarn returns true and warnAction is defined.
  • Similarly, it will only throw an InvalidField error if shouldThrow return true and throwMessage is defined.

Index Coverage Config

  • This config determines what to do if a query has insufficient coverage.
  • Setter: setIndexCheckHandler.

| Option | Type | Default | Definition | | ---- | ---- | ---- | ---- | | minCoverage | number | 0.25 | A floating number representing the percentage of fields that should be covered by an index. | | warnAction | (query: ViolatingQuery) => void | Log a warning message to console. | Given a violation query, define the warning action to run. | | throwMessage | (query: ViolatingQuery) => string | undefined | Given a violation query, return a message. This message will be wrapped in LowIndexCoverage error and thrown. |

  • The plugin will only run the warning action if shouldWarn returns true and warnAction is defined.
  • Similarly, it will only throw a LowIndexCoverage error if shouldThrow return true and throwMessage is defined.

Notes

  • All plugins created from the same SafeQuery instance share the configurations. Any update to the configurations will be shared by models whose schemas are configured with the same plugin.
  • For each query with the same fields, the warning action will only be run once. This is because usually you log the violating query in the warning action. This feature prevents the logging framework from being flooded by frequent queries.

References

License

ISC