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

@chargedcloud/crudgenerator

v2.0.2

Published

A Sequelize CRUD generator for Express.js

Downloads

706

Readme

@chargedcloud/crudgenerator

A package for you to create an API using Express and Sequelize (in relational databases) quickly and easily.

InstallationUsageRequests

Installation

You can install the package using npm:

npm install @chargedcloud/crudgenerator

Usage

Implementing services layer

In your services layer of your desired entity, you must import the serviceGenerator function. After you import it, you must call it passing the model of your entity as a parameter. The function will return an object with the following properties:

  • findAll: Function that returns all entities in the database.
  • findOne: Function that returns an entity in the database by its id.
  • create: Function that creates a new entity in the database.
  • updateById: Function that updates an entity in the database by its id.
  • remove: Function that removes an entity in the database by its id.
import db from "../models/index.mjs";
import createLogger from "@chargedcloud/logger";
import { serviceGenerator } from "@chargedcloud/crudgenerator";

// We recommended to use the createLogger function from @chargedcloud/logger
const log = createLogger(import.meta.url);

// Here you can declare your custom functions
const modelService = {};

const serviceMerged = serviceGenerator({
  modelName: "YourModel",
  dbInstance: db,
  service: modelService,
  multipleDb: false, // If you have multiple databases, put true
  logger: log, // The serviceGenerator function will use the createLogger function from @chargedcloud/logger, otherwise, put null
});

export default serviceMerged;

Multiple databases

If you have multiple databases, the serviceGenerator function will access the models instance using the property dbName via req.user. So, in your models layer, the index.mjs file must return an object with the following structure:

// index.mjs
export const db = {
  database1: {
    YourModel: ...
  },
  database2: {
    YourModel: ...
  }
}

After that, in your services layer, you must pass the dbName property in the req.user object via middleware and multipleDb parameter as true in the serviceGenerator function.

// middleware.mjs
export const middleware = (req, res, next) => {
  req.user = { dbName: "database1" };
  next();
};
// services/yourModelService.mjs
import db from "../models/index.mjs";

const serviceMerged = serviceGenerator({
  modelName: "YourModel",
  dbInstance: db,
  service: modelService,
  multipleDb: true,
});

OBSERVATION: The dbName property in the req.user object must be the same as the property in the db object.

Implementing controllers layer

Now, in your controllers layer, you must import the controllerGenerator function. After you import it, you must call it passing the service of your entity as a parameter. The function will return an object with the same properties of the service.

import { controllerGenerator } from "@chargedcloud/crudgenerator";
import modelService from "../services/yourModelService.mjs";

// Here you can declare your custom functions
const modelController = {};

const controllerMerged = controllerGenerator({
  service: modelService,
  controller: modelController,
});

export default controllerMerged;

Implementing routes layer

Finally, in your routes layer, you must import the routeGenerator function. After you import it, you must call it passing the controller of your entity as a parameter. The function will return an object with the routes of your entity.

import { Router } from "express";
import { routeGenerator } from "@chargedcloud/crudgenerator";
import modelController from "../controllers/yourModelController.mjs";

const modelRoutes = Router();

routeGenerator({
  router: modelRoutes,
  controller: modelController,
});

export default modelRoutes;

Requests

In this section, we will show you the different requests that you can make to the API and the responses that you will receive.

GET /yourModel

This request returns all entities in the database with pagination. The response will be an object with the following properties:

  • count: Number of entities in the database.
  • rows: Array with the entities in the database.
{
  "count": 1,
  "rows": [
    {
      "id": 1,
      "name": "John Doe",
      "createdAt": "2021-08-31T18:00:00.000Z",
      "updatedAt": "2021-08-31T18:00:00.000Z"
    }
  ]
}

Also, you can pass the following query parameters:

page

This parameter is used to indicate the page number of the entities that you want to get. The default value is 1.

pageLimit

This parameter is used to indicate the number of entities that you want to get per page. The default value is 20.

order

This parameter is used to indicate the order of the entities that you want to get. You can use the order parameter in the following ways:

OBSEVATION: We recommend that you JSON.stringify the order parameter in query string.

params: {
  order: JSON.stringify([
    // You can order the fields of the model
    { field: "name", direction: "ASC" },

    // Also, you can order the included models (how many nested levels you want)
    { modelsTarget: ["Comment"], field: "createdAt", direction: "DESC" },
  ]);
}

where

This parameter is used to indicate the conditions that the entities must meet to be returned. You can use the where parameter in the following ways:

OBSEVATION: We recommend that you JSON.stringify the where parameter in query string.

params: {
  where: JSON.stringify({
    // This is a optional parameter. The values are "AND" or "OR"
    operator: "OR",

    conditions: [
      // The default value of operator is eq
      { field: "name", operator: "substring", value: "John" },
      { field: "name", operator: "eq", value: "Doe" },
    ],
  });
}

include

This parameter is used to indicate the included models that you want to get. You can use the include parameter in the following ways:

OBSEVATION: We recommend that you JSON.stringify the include parameter in query string.

params: {
  include: JSON.stringify([
    // Simple include
    { model: "Comment", as: "comments" },

    // Nested include
    {
      model: "Comment",
      as: "comments",
      include: [{ model: "User", as: "user" }],
    },

    // Include with where
    {
      model: "Comment",
      as: "comments",
      where: {
        conditions: [
          { field: "content", operator: "substring", value: "Hello" },
          { field: "content", operator: "substring", value: "World" },
        ],
      },
    },
  ]);
}

GET /yourModel/:id

This request returns an entity in the database by its id. The response will be an object with the entity in the database.

{
  "id": 1,
  "name": "John Doe",
  "createdAt": "2021-08-31T18:00:00.000Z",
  "updatedAt": "2021-08-31T18:00:00.000Z"
}

POST /yourModel

This request creates a new entity in the database. The response will be an object with the entity in the database.

{
  "id": 1,
  "name": "John Doe",
  "createdAt": "2021-08-31T18:00:00.000Z",
  "updatedAt": "2021-08-31T18:00:00.000Z"
}

PATCH /yourModel/:id

This request updates an entity in the database by its id. The response will be an object with the entity in the database.

{
  "id": 1,
  "name": "John Doe",
  "createdAt": "2021-08-31T18:00:00.000Z",
  "updatedAt": "2021-08-31T18:00:00.000Z"
}

DELETE /yourModel/:id

This request removes an entity in the database by its id. The response will be an object with the entity in the database.

{ "id": 1 }