Express Mongoose Fast REST API
Quickly build RESTful APIs with Express and Mongoose.
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()
).
-
Require
Api
anderrorHandler
fromemfrest
const { Api, errorHandler } = require("emfrest");
-
Add the
errorHandler
middleware at the end of your app, beforeapp.listen()
.app.use(errorHandler);
-
Create an API using
Api
.Api(app, { model: Book, modelName: "book" });
Add your mongoose model as
model
, the example uses a model calledBook
.Also give it a
modelName
. The example usesmodelName
asbook
. This creates your routes at/books
. Make sure this is singular and unique among your routes. -
Start your server. It should show the following line on startup
Initialized api for book at /books
From scratch
-
Create a file
server.js
. -
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}`) );
-
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
andhandlePromiseRejections
later. -
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);
-
Add the
errorHandler
middleware at the end of your app, beforeapp.listen()
.app.use(errorHandler);
-
Create an API using
Api
.Api(app, { model: Book, modelName: "book" });
Add your mongoose model as
model
, the example uses a model calledBook
.Also give it a
modelName
. The example usesmodelName
asbook
. This creates your routes at/books
. Make sure this is singular and unique among your routes. -
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.
- Get All documents of a model with a query(optional).
- Create a document.
- Get a document by its ObjectId.
- Update a document by its ObjectId.
- Delete a document by its ObjectId.
Utilities
Utility functions to code faster
- Create an error object with a message and http status code.
- Connect to a MongoDB database.
- Promise rejection handler.