forked from GrafGenerator/gulp-json-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (99 loc) · 2.54 KB
/
index.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
'use strict';
var _ = require('lodash');
var jsonServer = require('json-server');
var utils = require('gulp-util');
var fs = require('fs');
var GulpJsonServer = function(options){
this.server = null;
this.instance = null;
this.router = null;
this.serverStarted = false;
this.options = {
data: 'db.json',
port: 3000,
rewriteRules: null,
baseUrl: null,
id: 'id',
deferredStart: false,
static: null
};
_.assign(this.options, options || {});
this.start = function () {
if(this.serverStarted){
utils.log('JSON server already started');
return this.instance;
}
var server = jsonServer.create();
if (this.options.static) {
server.use(jsonServer.defaults({static: this.options.static}));
} else {
server.use(jsonServer.defaults());
}
if(this.options.rewriteRules){
server.use(jsonServer.rewriter(this.options.rewriteRules));
}
var router = jsonServer.router(this.options.data);
if(this.options.baseUrl) {
server.use(this.options.baseUrl, router);
}
else{
server.use(router);
}
if(this.options.id){
router.db._.id = this.options.id;
}
this.server = server;
this.router = router;
this.instance = server.listen(this.options.port);
this.serverStarted = true;
return this.instance;
};
var ensureServerStarted = function(){
if(this.instance === null){
throw 'JSON server not started';
}
}.bind(this);
this.kill = function(){
ensureServerStarted();
this.instance.close();
};
this.reload = function(data){
ensureServerStarted();
var isDataFile = typeof this.options.data === 'string';
var newDb = null;
if(typeof(data) === 'undefined'){
if(!isDataFile){
// serving in-memory DB, exit without changes
return;
}
utils.log('reload from default file', utils.colors.yellow(this.options.data));
newDb = JSON.parse(fs.readFileSync(this.options.data));
}
else if(data !== null){
if(typeof data === 'string'){
// attempt to reload file
utils.log('reload from file', utils.colors.yellow(data));
newDb = JSON.parse(fs.readFileSync(data));
}
else{
// passed new DB object, store it
utils.log('reload from object');
newDb = data;
}
}
if(newDb === null){
throw 'No valid data passed for reloading. You should pass either data file path or new DB in-memory object';
}
this.router.db.object = newDb;
utils.log(utils.colors.magenta('server reloaded'));
};
// ==== Initialization ====
if(!this.options.deferredStart){
this.start();
}
};
module.exports = {
start: function(options){
return new GulpJsonServer(options);
}
};