-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
Β·138 lines (127 loc) Β· 3.95 KB
/
index.js
File metadata and controls
executable file
Β·138 lines (127 loc) Β· 3.95 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/env node
const jsonServer = require('json-server');
const cors = require('cors');
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const { watch } = require('node:fs/promises');
const path = require('path');
/**
* Watches the database file for changes and triggers router reload
* @param {string} dbFile - Path to the JSON database file
* @param {import('json-server').Router} router - JSON Server router instance
*/
async function watchDatabase(dbFile, router) {
try {
const watcher = watch(path.dirname(dbFile), { recursive: false });
console.log(`π Watching for changes in ${dbFile}`);
for await (const event of watcher) {
if (event.filename === path.basename(dbFile)) {
console.log('π Database changed, reloading...');
try {
// Clear require cache for the db file
delete require.cache[require.resolve(path.resolve(dbFile))];
// Reload the router's database
router.db.read();
console.log('β
Database reloaded successfully');
} catch (err) {
console.error('Error reloading database:', err);
}
}
}
} catch (err) {
console.error('Error watching database file:', err);
}
}
/**
* Creates and starts a JSON Server with user-provided configurations.
* @param {string} dbFile - Path to the JSON database file.
* @param {number} port - Port number to run the server on.
* @param {object} corsOptions - CORS configuration options.
* @returns {import('express').Express} The running JSON Server instance.
*/
const createJsonServer = (
dbFile = 'db.json',
port = 8080,
corsOptions = {}
) => {
const server = jsonServer.create();
const router = jsonServer.router(dbFile);
const middlewares = jsonServer.defaults();
// Apply CORS middleware if options are provided
server.use(cors(corsOptions));
// Use JSON Server middlewares and router
server.use(middlewares);
server.use(router);
// Start watching the database file
watchDatabase(dbFile, router);
// Start the server
server.listen(port, () => {
console.log(`π JSON Server is running at http://localhost:${port}`);
console.log(`π Using database file: ${dbFile}`);
});
return server;
};
// CLI Support
if (require.main === module) {
// When running from the command line
const argv = yargs(hideBin(process.argv))
.scriptName('json-server-setup')
.usage('Usage: $0 <dbFile> <port> [options]')
.command(
'$0 <dbFile> <port>',
'Start the JSON Server with the given configuration',
(yargs) => {
yargs
.positional('dbFile', {
describe: 'Path to the JSON database file',
type: 'string',
default: 'db.json',
})
.positional('port', {
describe: 'Port number to run the server on',
type: 'number',
default: 8080,
});
}
)
.option('cors-origin', {
describe: 'CORS origin(s) to allow (default: *)',
type: 'string',
default: '*',
})
.option('cors-methods', {
describe:
'Comma-separated list of allowed HTTP methods (default: GET, POST, PUT, DELETE)',
type: 'string',
default: 'GET, POST, PUT, DELETE',
})
.option('cors-headers', {
describe:
'Comma-separated list of allowed HTTP headers (default: Content-Type, Authorization)',
type: 'string',
default: 'Content-Type, Authorization',
})
.example('$0 db.json 5000', 'Start JSON Server on port 5000 using db.json')
.example(
'$0 db.json 5000 --cors-origin "http://localhost:3000"',
'Allow CORS requests from http://localhost:3000'
)
.help('h')
.alias('h', 'help')
.version('1.0.0')
.alias('v', 'version')
.epilog(
'For more information, visit https://github.com/wathika-eng/json-server-setup'
).argv;
// Extract CORS options
const corsOptions = {
origin: argv['cors-origin'],
methods: argv['cors-methods'],
allowedHeaders: argv['cors-headers'],
};
// Start the server
createJsonServer(argv.dbFile, argv.port, corsOptions);
} else {
// For use as a module in other Node.js apps or React development
module.exports = createJsonServer;
}