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

crud_api_generator

v1.0.4

Published

Generate CRUD api for your express.js project

Downloads

1

Readme

API GENERATOR

This package will generate CRUD API file for your provided database.Before using this package make sure you understand what it does.

Statement of Problem

It is time consuming when we write API code. It may take days to write all the fields for each table in your database. So this package will help write it for you.This package require express, sequelize and sequelize-auto to generate models directory in ./model.

Prerequisites

To make the API work please make sure you have generate models directory using sequelize-auto into ./model directory generate by script.

Install


npm install -g crud_api_generator
// currently support mysql database

Usage: apiGenerator -h <host>  -p <port> -u <username> --pw <password> --db <database>

Options:
      --version         Show version number                            [boolean]
  -h, --host            Can be your database IP address                 [string]
  -p, --port            Port to your database                           [string]
  -u, --username        Database Username                               [string]
      --pw, --password  Database Password                               [string]
      --db, --database  Database name                                   [string]
      --help            Show help                                      [boolean]

It will produce a file app.js in your root directory so make sure you backup your app.js file before running it. The file will looks like this:

const express = require('express')
const app = express()
const PORT = 3000;

app.use(express.json());
 
app.use(express.urlencoded({ extended: true }));

const [table name] = require('./router/[Your table name]')
app.use([table name])

app.listen(PORT,function(e){
    if(e) console.log(e)
    console.log("server listen on PORT ", PORT)
})

It will produce a file auth.js in your root directory. This file is to handle all the authentication for your API. The file look like this:

exports.authenticate = (req,res,next)=>{
    ///// Check Authentication Here /////
    return next()
}

It will produce a directory call ./router/[table name].js. The file look like this:

const express = require('express')
const router = express.Router()
const model = require('../model/index')
const authentication = require('../auth')
router.use(authentication.authenticate)

    
router.post('/api/insert/[table name]',(req,res)=>{
    let dataToProcess = new Object();
   if(req.body.[column_name]) dataToProcess['[column_name]'] = req.body.[column_name];

    model.[table name].create(
        dataToProcess
    )
    .then((result)=>{
        res.status(200).send(result)
    })
    .catch((e)=>{
        res.status(500).send(e)
    });
})

router.get('/api/get_all/[table name]',(req,res)=>{
    model.[table name].findAll()
    .then((result)=>{
        res.status(200).send(result)
    })
    .catch((e)=>{
        res.status(500).send(e)
    });
})

router.get('/api/get/[table name]/:id',(req,res)=>{
    model.[table name].findAll({
        where:{
            id:req.params.id
        }
    })
    .then((result)=>{
        res.status(200).send(result)
    })
    .catch((e)=>{
        res.status(500).send(e)
    });
})

router.patch('/api/update/[table name]/:id',(req,res)=>{
    let dataToProcess = new Object();
   if(typeof(req.body.[column_name]) !== 'undefined') dataToProcess['[column_name]'] = req.body.[column_name];

    model.[table name].update({
        dataToProcess,
        where:{
            id:req.params.id
        }
    })
    .then((result)=>{
        res.status(200).send(result)
    })
    .catch((e)=>{
        res.status(500).send(e)
    });
})

router.delete('/api/delete/[table name]/:id',(req,res)=>{
    model.[table name].destroy({
        where:{
            id:req.params.id
        }
    })
    .then((result)=>{
        res.status(200).send(result)
    })
    .catch((e)=>{
        res.status(500).send(e)
    });
})

module.exports = router;

It will produce a directory call ./model/index.js. The file look like this:

const { Sequelize } = require('sequelize');
const initModels = require("./models/init-models")
// make sure you have set up your process.env
const db = process.env.DATABASE
const us = process.env.USER_NAME
const ps = process.env.PASSWORD
const host = process.env.HOST
const port = process.env.PORT
const sequelize = new Sequelize(db, us, ps, {
    host: host,
    port: port,
    // one of our supported dialects:
    // 'mysql', 'mariadb', 'postgres', 'mssql', 'sqlite', 'snowflake', 'db2' or 'ibmi'
    dialect: 'mysql',
    // set up connection pool
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
});

const models = initModels(sequelize);

// We export the sequelize connection instance to be used around our app.
module.exports = models;

Authors

License

This project is licensed under the MIT License - see the LICENSE file for details

Reference