Lesson 28-Node Comprehensive Applications

Watch Service

const fs = require('fs');
const exec = require('child_process').exec;

function watch() {
  const child = exec('node server.js');
  const watcher = fs.watch(__dirname + '/server.js', function () {
    console.log('File changed, reloading.');
    child.kill();
    watcher.close();
    watch();
  });
}

watch();

RESTful Web Application

  • REST stands for Representational State Transfer.
  • Use correct HTTP methods, URLs, and headers to create semantic RESTful APIs.
  • GET /pages: Retrieve
  • POST /pages: Create
  • GET /pages/10: Retrieve page 10
  • PATCH /pages/10: Update page 10
  • PUT /pages/10: Replace page 10
  • DELETE /pages/10: Delete page 10
let app;
const express = require('express');
const routes = require('./routes');

module.exports = app = express();

app.use(express.json()); // Parse JSON body
app.use(express.methodOverride()); // Allow query parameter to specify additional HTTP methods

// Routes for resources
app.get('/pages', routes.pages.index);
app.get('/pages/:id', routes.pages.show);
app.post('/pages', routes.pages.create);
app.patch('/pages/:id', routes.pages.patch);
app.put('/pages/:id', routes.pages.update);
app.delete('/pages/:id', routes.pages.remove);

Middleware Application

const express = require('express');
const app = express();
const Schema = require('validate');
const xml2json = require('xml2json');
const util = require('util');
const Page = new Schema();

Page.path('title').type('string').required(); // Data validation ensures page has a title

function ValidatorError(errors) { // Inherit from Error object, handle validation errors in error middleware
  this.statusCode = 400;
  this.message = errors.join(', ');
}
util.inherits(ValidatorError, Error);

function xmlMiddleware(req, res, next) { // Middleware to handle XML
  if (!req.is('xml')) return next();

  let body = '';
  req.on('data', function (str) { // Triggered when data is read from client
    body += str;
  });

  req.on('end', function () {
    req.body = xml2json.toJson(body.toString(), {
      object: true,
      sanitize: false,
    });
    next();
  });
}

function checkValidXml(req, res, next) { // Data validation middleware
  const page = Page.validate(req.body.page);
  if (page.errors.length) {
    next(new ValidatorError(page.errors)); // Pass error to next to stop route execution
  } else {
    next();
  }
}

function errorHandler(err, req, res, next) { // Error handling middleware
  console.error('errorHandler', err);
  res.status(err.statusCode || 500).send(err.message);
}

app.use(xmlMiddleware); // Apply XML middleware to all requests

app.post('/pages', checkValidXml, function (req, res) { // Validate XML for specific requests
  console.log('Valid page:', req.body.page);
  res.send(req.body);
});

app.use(errorHandler); // Add error handling middleware

app.listen(3000);

Share your love