create a complete crud interface for generic object with rest api in javascript

To create a CRUD interface for a generic object with REST API, you can follow these steps:

  1. Install required dependencies:

    index.tsx
    npm install express mongoose body-parser
    
    41 chars
    2 lines
  2. Create a server.js file and import required modules:

    index.tsx
    const express = require('express');
    const bodyParser = require('body-parser');
    const mongoose = require('mongoose');
    
    117 chars
    4 lines
  3. Connect to MongoDB database:

    index.tsx
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost:27017/mydb', {
       useNewUrlParser: true,
       useUnifiedTopology: true
    }).then(() => {
       console.log("Connected to the database");
    }).catch(err => {
       console.log("Cannot connect to the database", err);
       process.exit();
    });
    
    299 chars
    11 lines
  4. Create a mongoose schema for your object:

    index.tsx
    const MyObjectSchema = mongoose.Schema({
       name: String,
       description: String
    }, {
       timestamps: true
    });
    
    const MyObject = mongoose.model('MyObject', MyObjectSchema);
    
    172 chars
    9 lines
  5. Create routes for CRUD operations:

    index.tsx
    const app = express();
    app.use(bodyParser.json());
    
    // Create a new MyObject
    app.post('/myobjects', (req, res) => {
       const myobject = new MyObject({
          name: req.body.name,
          description: req.body.description
       });
    
       myobject.save().then(data => {
          res.send(data);
       }).catch(err => {
          res.status(500).send({
             message: err.message || "Some error occurred while creating the MyObject."
          });
       });
    });
    
    // Retrieve all MyObjects
    app.get('/myobjects', (req, res) => {
       MyObject.find().then(myobjects => {
          res.send(myobjects);
       }).catch(err => {
          res.status(500).send({
             message: err.message || "Some error occurred while retrieving MyObjects."
          });
       });
    });
    
    // Retrieve a single MyObject
    app.get('/myobjects/:myobjectId', (req, res) => {
       MyObject.findById(req.params.myobjectId).then(myobject => {
          if (!myobject) {
             return res.status(404).send({
                message: "MyObject not found with id " + req.params.myobjectId
             });
          }
          res.send(myobject);
       }).catch(err => {
          if (err.kind === 'ObjectId') {
             return res.status(404).send({
                message: "MyObject not found with id " + req.params.myobjectId
             });
          }
          return res.status(500).send({
             message: "Error retrieving MyObject with id " + req.params.myobjectId
          });
       });
    });
    
    // Update a MyObject
    app.put('/myobjects/:myobjectId', (req, res) => {
       MyObject.findByIdAndUpdate(req.params.myobjectId, {
          name: req.body.name,
          description: req.body.description
       }, { new: true }).then(myobject => {
          if (!myobject) {
             return res.status(404).send({
                message: "MyObject not found with id " + req.params.myobjectId
             });
          }
          res.send(myobject);
       }).catch(err => {
          if (err.kind === 'ObjectId') {
             return res.status(404).send({
                message: "MyObject not found with id " + req.params.myobjectId
             });
          }
          return res.status(500).send({
             message: "Error updating MyObject with id " + req.params.myobjectId
          });
       });
    });
    
    // Delete a MyObject
    app.delete('/myobjects/:myobjectId', (req, res) => {
       MyObject.findByIdAndRemove(req.params.myobjectId).then(myobject => {
          if (!myobject) {
             return res.status(404).send({
                message: "MyObject not found with id " + req.params.myobjectId
             });
          }
          res.send({ message: "MyObject deleted successfully!" });
       }).catch(err => {
          if (err.kind === 'ObjectId' || err.name === 'NotFound') {
             return res.status(404).send({
                message: "MyObject not found with id " + req.params.myobjectId
             });
          }
          return res.status(500).send({
             message: "Could not delete MyObject with id " + req.params.myobjectId
          });
       });
    });
    
    // Start the server
    app.listen(3000, () => {
       console.log("Server is listening on port 3000");
    });
    
    2950 chars
    101 lines
  6. Test your CRUD API interface using POSTman or similar tool.

That's it! You now have a complete CRUD interface for generic objects with a REST API in JavaScript.

gistlibby LogSnag