# all files / lib/routes/ generate.js

11.54% Statements 3/26
0% Branches 0/10
0% Functions 0/6
11.54% Lines 3/26

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    1×

    1×

    1×
     // jscs:disable jsDoc
    var _ = require('lodash'),
    	fs = require('fs'),
    	path = require('path'),
    	mkdirp = require('mkdirp'),
    	util = require('../util');

    function configure(arrow, app, config, prefix) {

    	var token = String(Date.now());

    	if (config.env === 'development') {

    		// re-generate the token when restarted
    		arrow.on('stopped', function () {
    			token = String(Date.now());
    		});

    		app.get(prefix + '/generate/token/:token', function (req, resp, next) {
    			return resp.json({
    				// if the same token is passed back, we haven't yet restarted
    				// if it's different, we're good
    				success: req.params.token !== token
    			});
    		});

    		app.post(prefix + '/generate/model/:name', function (req, resp, next) {
    			var filename = util.generateModelName(config, req.params.name),
    				dirname = path.dirname(filename);

    			mkdirp(dirname, function (err) {
    				if (err) {
    					return util.json(resp, {
    						success: false,
    						message: err.message
    					});
    				}

    				if (req.query.originalModelName) {
    					var original = req.query.originalModelName.replace(/[/\\]/g, '');
    					var originalFilename = util.generateModelName(config, original);
    					if (fs.existsSync(originalFilename)) {
    						fs.unlinkSync(originalFilename);
    					}
    				}
    				var suffix = 1;
    				while (fs.existsSync(filename)) {
    					filename = util.generateModelName(config, req.params.name + (++suffix));
    				}
    				fs.writeFile(filename, req.body, function (err) {
    					if (err) {
    						return util.json(resp, {
    							success: false,
    							message: err.message
    						});
    					} else {
    						// send back the started timestamp as a token
    						return util.json(resp, {
    							success: true,
    							token: token
    						});
    					}
    				});
    			});
    		});
    	}
    }

    exports.configure = configure;