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

mongorester

v1.0.17

Published

Generate a Mongoose Model and Crud Routes with one function also includes authy function which can spin up JWT authentication

Downloads

23

Readme

Mongo Rester

by Alex Merced

Spin up a Full Crud Mongo Express API with one function

How it works

Install it...

npm install mongorester

require it...

const { rester } = require("mongorester");

Pass the rester function a model name string and schema definition object. The function will return an array with the model and the router with 5 pre-made routes.

//Generate Model and Router
const [Note, noteRouter] = rester("Note", { title: String, content: String });

//add extra routes if you want
noteRouter.get("/user/:username", async (req, res) => {
  res.json(await Note.find({ username: req.params.username }));
});

//Use the Router
app.use("/note/", noteRouter);

The Pre-Made Routes

Here is the Routes that get created when using the rester function

//INDEX
router.get("/", async (req, res) => {
  try {
    res.status(200).json(await Model.find({}));
  } catch (error) {
    res.status(400).json({ error });
  }
});

//SHOW
router.get("/:id", async (req, res) => {
  try {
    res.status(200).json(await Model.findById(req.params.id));
  } catch (error) {
    res.status(400).json({ error });
  }
});

//CREATE
router.post("/", async (req, res) => {
  try {
    res.status(200).json(await Model.create(req.body));
  } catch (error) {
    res.status(400).json({ error });
  }
});

//PUT
router.put("/:id", async (req, res) => {
  try {
    res
      .status(200)
      .json(await Model.findByIdAndUpdate(req.params.id, req.body));
  } catch (error) {
    res.status(400).json({ error });
  }
});

//DELETE
router.delete("/:id", async (req, res) => {
  try {
    res.status(200).json(await Model.findByIdAndRemove(req.params.id));
  } catch (error) {
    res.status(400).json({ error });
  }
});

The Config Object

Can pass a third config object argument that'll help add middleware and configure your schema.

//config object
const config = {
  middleware: [auth], //array of middleware function, must be an array
  config: { timestamps: false }, //second argument of Schema, default timestamps true
  indexQuery: (req, res) => {
    username: req.query.username;
  },
  //Function that takes req/res and returns object to query for index route
};

//Generate Model and Router
const [Note, noteRouter] = rester(
  "Note",
  { title: String, content: String },
  config
);

Overriding Default Routes

You can pass an alternate route handler into the config object under the following keys:

  • index
  • show
  • update
  • create
  • destroy

with the following function signature

(req, res, model) => {}

authy

Another function inside Mongo Rester is Authy which will quickly implement JWT user authentication. (uses a bearer token)

const { authy } = require("mongorester");

Using it is as easy as this...

userSchema = {
  username: String,
  password: String,
  email: String,
};

schemaConfig = {
  timestamps: true,
};

options = {
  secret: "cheese",
  tokenConfig: {
    expiresIn: "1h",
  },
};

const [User, authMiddleware, authRouter, authRester] = authy(
  userSchema,
  schemaConfig,
  options
);

User: The user model.

authMiddleware: Middleware functions to protect routes. It will store the token payload in req.payload

authRouter: auth router with "/register" and "/login" post routes. THe login route will generate a token that holds all the user object except the password.

authRester: Like the rester function except it applies the authMiddleware to all routes, already has all CRUD routes like rester.

connmon

Simple Mongo connection simplifier. Just pass it your mongo uri and it will return the connected mongoose object with basic event logs for open, close and error.

const { connmon, rester, authy } = require("mongorester");

const mongoose = connmon(uri);

reqInjector

Pass it a key and data and it will inject that data into the request object under that key. It returns a middleware function.

const { reqInjector } = require("mongorester");
const { User, Blog } = require("./models");

//This makes all models available to all routes inside req.models
app.use(reqInjector("models", { User, Blog }));

cbLog

In a lot of situations you have to pass a callback (think app.listen) which often just contains a console.log, so cbLog is a quick way to pass these messages in a colorful way.

cbLog(key, message)

const {cbLog} = require("mongorester")

app.listen(PORT, cbLog("server", `Listening on ${PORT})`)