client/data/simple-persist.js
author rougeronj
Tue, 22 Sep 2015 15:14:10 +0200
changeset 543 5f7bebdcfc0d
parent 356 763c925e7a9c
child 647 eaaa1efce396
permissions -rw-r--r--
Improve the way we init the view. The data loader send a "loaded" event, hooked by the scene.py and initializing the backbone.history and the view. We don't use redraw_active in save-once and full-json, because it was making the view initialization dependent of these file which are externals. Small fix to hide the "set saved view" button when there is only one view.

// Simple persist middle ware
var path = require('path'),
    fs = require('fs');

var jsonFile = path.join(__dirname,"example-cinema.json");
var resetFile = path.join(__dirname,"example-cinema-src.json");

exports.middleware = function(req, res, next) {
    'use strict';

    if (req.url !== '/simple-persist') {
      return next();
    }

    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    res.statusCode = 200;

    if(req.method === "PUT" || req.method === "POST") {
      req.pipe(fs.createWriteStream(jsonFile));
      setTimeout(function () {
    	  res.end(JSON.stringify({result: "OK"}));
      }, 3000);
    }
    else {
      var params = require('url').parse(req.url),
          readStream;
      if('reset' in params && params.reset) {
        readStream = fs.createReadStream(resetFile);
        readStream.pipe(fs.createWriteStream(jsonFile));
      }
      else {
        readStream = fs.createReadStream(jsonFile);
        readStream.on('error',function() {
          var srcFile = fs.createReadStream(resetFile);
          srcFile.pipe(fs.createWriteStream(jsonFile));
          srcFile.pipe(res);
        });
      }
      readStream.pipe(res);
    }
};