All Projects → cktang88 → mongoose-api-generator

cktang88 / mongoose-api-generator

Licence: MIT license
Autogenerate a REST API from your Mongoose models

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
CSS
56736 projects
HTML
75241 projects

Projects that are alternatives of or similar to mongoose-api-generator

mongoose-auto-increment-reworked
An auto-incrementing field generator for Mongoose 4 & 5
Stars: ✭ 17 (-10.53%)
Mutual labels:  mongoose, db
derivejs
DeriveJS is a reactive ODM - Object Document Mapper - framework, a "wrapper" around a database, that removes all the hassle of data-persistence by handling it transparently in the background, in a DRY manner.
Stars: ✭ 54 (+184.21%)
Mutual labels:  mongoose, db
ark.db
Small and fast JSON database for Node and browser. 😋
Stars: ✭ 65 (+242.11%)
Mutual labels:  mongoose, db
Typegoose
Typegoose - Define Mongoose models using TypeScript classes.
Stars: ✭ 1,189 (+6157.89%)
Mutual labels:  mongoose, db
build-and-secure-restful-api
Source code for 'Build and Secure Restful API in Node.js, Express and MongoDB' course
Stars: ✭ 42 (+121.05%)
Mutual labels:  mongoose
xiaomishop
基于nodejs web框架egg.js+mongoose实现的仿小米商城的项目
Stars: ✭ 26 (+36.84%)
Mutual labels:  mongoose
sqllex
The most pythonic ORM (for SQLite and PostgreSQL). Seriously, try it out!
Stars: ✭ 80 (+321.05%)
Mutual labels:  db
Nest Mean
NestJS Tutorial Repository
Stars: ✭ 250 (+1215.79%)
Mutual labels:  mongoose
amazin
A MERN-stack app for eCommerce platform, Webshop, Web Store. Storybook: https://www.amazin.one/ Alternative: https://ntrix.github.io/amazin-story
Stars: ✭ 27 (+42.11%)
Mutual labels:  mongoose
underbase
MongoDB schema and data migration library based on semver
Stars: ✭ 19 (+0%)
Mutual labels:  mongoose
erkab-web-app
Erkab - A student centric ride sharing website.
Stars: ✭ 21 (+10.53%)
Mutual labels:  mongoose
nestjs-api-mongoose
Collection example apps with NestJS and Typeorm, Sequelize, Mongodb, PostgreSQL, MySQL, GraphQL, Mercurius, etc. for the NestJS community 😻
Stars: ✭ 153 (+705.26%)
Mutual labels:  mongoose
vulkano
A small, simple and fast framework for creating web applications using NodeJS. Inspired by KumbiaPHP.
Stars: ✭ 15 (-21.05%)
Mutual labels:  mongoose
morest
Allows developers to quickly create RESTful APIs using MongoDB and Express.
Stars: ✭ 14 (-26.32%)
Mutual labels:  mongoose
mongodb-tree-structure
Implementing Tree Structure in MongoDB
Stars: ✭ 14 (-26.32%)
Mutual labels:  mongoose
Express Mongoose Es6 Rest Api
💥 A boilerplate application for building RESTful APIs Microservice in Node.js using express and mongoose in ES6 with code coverage and JsonWebToken Authentication
Stars: ✭ 2,811 (+14694.74%)
Mutual labels:  mongoose
react-redux-passport-uikit-express-boiler
A React+Redux boilerplate using Express as backend, UIKit for frontend, MongoDB for storage & Passport for auth.
Stars: ✭ 59 (+210.53%)
Mutual labels:  mongoose
koa-mongoDB
😊😊Koa and mongoose build services
Stars: ✭ 24 (+26.32%)
Mutual labels:  mongoose
mern-graphql-jwt
MERN stack with GraphQL tutorial.
Stars: ✭ 17 (-10.53%)
Mutual labels:  mongoose
tool-db
A peer-to-peer decentralized database
Stars: ✭ 15 (-21.05%)
Mutual labels:  db

Mongoose REST API Autogenerator

Automatically generate a REST API from Mongoose models.

Creates a hot-reloading server that auto-updates whenever models are updated or created.

⚠️ This project is still in an early stage and may undergo breaking changes.

Dev

Create a .env file with

# url of mongo database
MONGODB_URL='<url_of_mongo_database>'

# jwt signing secret for auth
JWT_SECRET = '<signing_secret>'

# directory models are discovered from (optional)
# ./models by default
MODELS_DIR = 'models'

# the path of the autogenerated resources enum file for the client (optional)
# ./client/src by default
RESOURCES_FILE_DIR = 'client/src'

Then:

yarn
yarn start

Client library

This repo includes a sample frontend (React + TypeScript) at ./client. This is a bare React app made with create-snowpack-app using the @snowpack/app-template-react-typescript template.

There are two custom files included to make API requests easier.

  • client/src/apiLib.ts - exports helpful functions to easily interact with the API.
  • client/src/apiResources.ts - contains an exported TypeScript enum made to work with apiLib.ts that is autogenerated from your models, and is hot-reloaded as well.

Sample usage:

// Resource is an enum exported by './apiResources.ts'
import { signup, login, api, Resource } from "./apiLib";

// signup and login :)
await signup("bob", email, password);
await login(email, password);

// create a new box
let box = await api.CREATE(Resource.box, { height: 4 });
// get a new box
box = await api.GET(Resource.box, box._id);
// list all boxes
box = await api.LIST(Resource.box);

// api.UPDATE and api.DELETE is also available.

Authentication

  • Sign up:

    • POST /auth/signup
    • Sample request body:
      {"username": "bob", "email": "[email protected]", "password": "badpw"}
      
  • Login:

    • POST /auth/login
    • Sample request body:
      {"email": "[email protected]", "password": "badpw"}
      
      • returns a JWT token, eg. Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlZWQ3OWM1N2MxZmEzNzExODZlZjljOSIsInVzZXJuYW1lIjoiYWIiLCJpYXQiOjE1OTI2MjI1MDAsImV4cCI6MTU5MjY1ODUwMH0.-eFJ1FcotHsjtmgUaE3f-6fFz_7y8c2dCNqhH8E5S6A
    • Pass the token in the Authorization HTTP header for each subsequent API request.
  • View user profile via GET /auth/profile

Adding a model

Simply create a new file that exports a mongoose model to ./models.

This will result in two actions:

  1. autogenerated URL endpoints will be updated
  2. An autogenerated file will be created/overriden at ${RESOURCES_FILE_DIR}/apiResources.ts.

NOTE: these endpoints are not accessible unless you are signed in. The autogenerated URL endpoints will be:

Create:

  • POST /api/{fileName}
    • Inputs are automatically validated using the Mongoose Schema. Errors are returned to the client with a 400 HTTP Error code.

List all

  • GET /api/{fileName}

Get one

  • GET /api/{fileName}/:id

Update one

  • PATCH /api/{fileName}/:id

Delete one

  • DELETE /api/{fileName}/:id

Implementing permissions

Permissions enable you to implement granular restrictions on who can perform an action on a resource.

  • need to have an owner_id: String field in the Mongoose Schema. This field is automatically populated whenever a new object is created via the API endpoint.

  • Export a permissions object that may override list/get/update/remove fields (by default all of these are set to PUBLIC)

    • possible values (exported from "../framework/auth/permissions"):
      • PUBLIC: anyone can perform this action on this resource
      • OWNER: only the creator of the resource can perform this action
      • NONE: this action is disabled for this object
  • Example:

const { Schema } = require("mongoose");
const { PUBLIC, OWNER, NONE } = require("../framework/auth/permissions");
const schema = new Schema(
  {
    width: Number,
    height: Number,
    created: { type: Date, default: Date.now },
    name: String,
    owner_id: String,
  },
  { strict: "throw" }
);

const permissions = {
  list: PUBLIC,
  get: PUBLIC,
  update: OWNER,
  remove: NONE,
};

module.exports = { schema, permissions };

Tech used

  • Mongoose, Express, Passport
  • Nodemon is used for hot-reloading instead of node-dev because the files are dynamically required, so file-watching is needed to identify new files being added but not specifically required in ./models.

TODOs

  • enable extensibility for login object? (eg. phone num, descript, other meta fields)
  • sanitize all inputs in express middleware...
  • support listing with filtering?
  • auto-add owner_id: String and { strict: "throw", toObject: { versionKey: false } } using Mongoose discriminators for schema inheritance?
  • enable disabling all auth for all endpoints via config var
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].