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

emfrest

v1.1.3

Published

Quickly build RESTful APIs with Express and Mongoose.

Downloads

5

Readme

Express Mongoose Fast REST API

Quickly build RESTful APIs with Express and Mongoose.

Documentation

Github

npm

Have a look at the list of service and utility functions and other middleware and global functions.

Installation

npm i emfrest

This also installs express and mongoose, so you can dive right into making your API.

Usage

Basic

Create an API using Api.

const { Api } = require("emfrest");

Api(app, { model: Book, modelName: "book" });

Add your mongoose model as model, the example uses a model called Book.

Also give it a modelName. The example uses modelName as book. This creates your routes at /books. Make sure this is singular and unique among your routes.

For every Api you create, you will get the following routes:

| Method | Route | | :----- | :------------- | | GET | /books | | POST | /books | | GET | /books/:bookId | | PUT | /books/:bookId | | DELETE | /books/:bookId |

Adding endpoint specific middleware

You can also have endpoint specific middleware. The preMiddleware option takes an array of Middlewares that will run before the controller function.

Api(app, {
  model: Book,
  modelName: "book",
  preMiddleware: [
    protect,
    myMiddlewareFunction1,
    myMiddlewareFunction2 /*...*/,
  ],
});

Route prefix for an endpoint

If you want to serve the API from a subpath, you can use the routePrefix option.

const { Api } = require("emfrest");

Api(app, { model: Book, modelName: "book", routePrefix: "/v1" });

This would result in the following routes

| Method | Route | | :----- | :---------------- | | GET | /v1/books | | POST | /v1/books | | GET | /v1/books/:bookId | | PUT | /v1/books/:bookId | | DELETE | /v1/books/:bookId |

Add to an existing app

Note: App should be connected to a database. App should also be able to read json data from requests (body-parser or express.json()).

  1. Require Api and errorHandler from emfrest

    const { Api, errorHandler } = require("emfrest");
  2. Add the errorHandler middleware at the end of your app, before app.listen().

    app.use(errorHandler);
  3. Create an API using Api.

    Api(app, { model: Book, modelName: "book" });

    Add your mongoose model as model, the example uses a model called Book.

    Also give it a modelName. The example uses modelName as book. This creates your routes at /books. Make sure this is singular and unique among your routes.

  4. Start your server. It should show the following line on startup

    Initialized api for book at /books

From scratch

  1. Create a file server.js.

  2. Add your express boilerplate code.

    const express = require("express");
    
    const app = express();
    
    app.use(express.json());
    
    app.get("/", (req, res) => {
      res.json({ success: true, message: "Check your api endpoint" });
    });
    
    const PORT = process.env.PORT || 3000;
    const server = app.listen(PORT, () =>
      console.log(`Server started on port ${PORT}`)
    );
  3. Connect to MongoDB

    const {
      Api,
      connectDB,
      errorHandler,
      handlePromiseRejections,
    } = require("emfrest");
    
    connectDB("mongodb://localhost:27017/library");

    You can use a connection string of your choice.

    We will use Api, errorHandler and handlePromiseRejections later.

  4. Create your schema and mongoose model.

    const mongoose = require("mongoose");
    
    const BookSchema = new mongoose.Schema({
      name: {
        type: String,
      },
      description: {
        type: String,
      },
    });
    
    const Book = mongoose.model("Book", BookSchema);
  5. Add the errorHandler middleware at the end of your app, before app.listen().

    app.use(errorHandler);
  6. Create an API using Api.

    Api(app, { model: Book, modelName: "book" });

    Add your mongoose model as model, the example uses a model called Book.

    Also give it a modelName. The example uses modelName as book. This creates your routes at /books. Make sure this is singular and unique among your routes.

  7. Handle promise rejections

    handlePromiseRejections(server);

Your code should now look like this:

const express = require("express");
const {
  Api,
  connectDB,
  errorHandler,
  handlePromiseRejections,
} = require("emfrest");

connectDB("mongodb://localhost:27017/library");

const mongoose = require("mongoose");

const BookSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

const Book = mongoose.model("Book", BookSchema);

const app = express();

app.use(express.json());

Api(app, { model: Book, modelName: "book" });

app.get("/", (req, res) => {
  res.json({ success: true, message: "Check your api endpoint" });
});

app.use(errorHandler);

const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () =>
  console.log(`Server started on port ${PORT}`)
);

handlePromiseRejections(server);

Reusable Functions

Services

Service functions are used to make calls to your MongoDB database using your mongoose model.

  1. Get All documents of a model with a query(optional).
  2. Create a document.
  3. Get a document by its ObjectId.
  4. Update a document by its ObjectId.
  5. Delete a document by its ObjectId.

Utilities

Utility functions to code faster

  1. Create an error object with a message and http status code.
  2. Connect to a MongoDB database.
  3. Promise rejection handler.

Liked emfrest?

Enjoyed making your APIs faster? Star efmrest on Github.