mongoose-api-generator

Autogenerate a REST API from your Mongoose models

View the Project on GitHub cktang88/mongoose-api-generator

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.

:warning: 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.

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

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:

List all

Get one

Update one

Delete one

Implementing permissions

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

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

TODOs