Introduction to Querymen Enhancing APIs With Comprehensive Code Examples

Introduction to Querymen

Querymen is a Node.js module designed to parse and validate the query string of requests, enabling streamlined API development and enhancing query management in your applications. Below, we delve into an introduction to Querymen, highlighting its practical APIs through informative code snippets.

Installation

  
    npm install querymen
  

Creating a Simple App with Querymen

Let’s create a basic Express app using Querymen:

  
    const express = require('express');
    const { middleware: querymen } = require('querymen');

    const app = express();
    
    app.get('/movies', querymen({ genre: String, year: Number }), (req, res) => {
      const { query } = req;
      res.json({ message: 'Movies fetched successfully', query });
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  

APIs and Code Snippets

Query Parsing and Validation

This API allows the parsing and validation of query strings. By defining schemas, you can ensure that the incoming queries match the required format:

  
    const schema = new Querymen.Schema({
      name: {
        type: String,
        required: true
      },
      age: {
        type: Number
      }
    });

    app.get('/users', querymen(schema), (req, res) => {
      // Access validated query with req.querymen.query
      res.send(req.querymen.query);
    });
  

Schema Options

Querymen allows extensive schema definitions such as specifying defaults, enumerations, and custom validation functions:

  
    const schema = new Querymen.Schema({
      category: {
        type: String,
        enum: ['Action', 'Drama', 'Comedy'],
        required: true
      },
      date: {
        type: Date,
        default: Date.now
      },
      rating: {
        type: Number,
        validate: (val) => val >= 0 && val <= 10
      }
    });

    app.get('/reviews', querymen(schema), (req, res) => {
      res.json(req.querymen.query);
    });
  

Pagination and Sorting

Implement Pagination and Sorting effortlessly with Querymen using the ‘cursor’ option for automatic parsing of pagination and sorting queries:

  
    const querySchema = new Querymen.Schema({});

    app.get('/products', querymen(querySchema, { cursor: true }), (req, res) => {
      // Access pagination and sorting parameters
      const { limit, skip, sort } = req.querymen.cursor;
      res.json({ limit, skip, sort });
    });
  

Combining Filters

Combining filters and applying them seamlessly to a MongoDB collection:

  
    const querySchema = new Querymen.Schema({
      title: String,
      published: Boolean,
      rating: {
        type: Number,
        min: 0,
        max: 5
      }
    });

    app.get('/books', querymen(querySchema), async (req, res) => {
      const books = await Book.find(req.querymen.query);
      res.json(books);
    });
  

Full Working Example

Here is a full working example combining various Querymen features:

  
    const express = require('express');
    const mongoose = require('mongoose');
    const { middleware: querymen } = require('querymen');
    
    const app = express();
    mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });

    const itemSchema = new mongoose.Schema({
      name: String,
      price: Number,
      category: String,
      inStock: Boolean
    });

    const Item = mongoose.model('Item', itemSchema);

    const querySchema = new Querymen.Schema({
      name: { type: RegExp, paths: ['name'] },
      price: Number,
      category: String,
      inStock: Boolean
    });

    app.get('/items', querymen(querySchema, { cursor: true }), async (req, res) => {
      const items = await Item.find(req.querymen.query)
        .limit(req.querymen.cursor.limit)
        .skip(req.querymen.cursor.skip)
        .sort(req.querymen.cursor.sort);
      res.json(items);
    });

    app.listen(4000, () => {
      console.log('Server running on http://localhost:4000');
    });
  

By combining the advantages of Querymen’s query parsing with Express, you can build efficient and scalable APIs. Querymen simplifies the normalization, validation, and pagination of API query parameters, making it a valuable addition to the Node.js developer’s toolkit.

Hash: 37b78a50ba49ab684ee15e6fed818d9e46ccd94e769df7f40bc2abedf0732965

Leave a Reply

Your email address will not be published. Required fields are marked *