-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
178 lines (160 loc) · 5.87 KB
/
mod.ts
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/**
* @file Deno entry point for @webmasterdevlin/json-server
*
* This module provides a Deno-compatible interface for json-server.
* It can be used both as a CLI and as a programmatic API from Deno scripts.
*
* Features include:
* - TypeScript-powered JSON Server with API prefix support
* - RESTful API with custom routes
* - Configurable settings for CORS, delay, read-only mode
* - API prefix (/api/*) routing via the enableApiPrefix option
*
* @example
* // Run from command line:
* // deno run --allow-read --allow-write --allow-net --allow-run mod.ts db.json --port 3001 --enable-api-prefix
*
* // Import programmatically:
* // import { create } from "./mod.ts";
* // const server = create({ port: 3000, enableApiPrefix: true });
* // server.loadDatabase("./db.json");
* // await server.start();
*
* @author webmasterdevlin
* @copyright MIT License
*/
import { parse } from 'npm:minimist';
import { create, JsonServer, ServerOptions } from 'npm:@webmasterdevlin/json-server';
/**
* Display help information for Deno usage
*/
function showHelp(): void {
console.log(`
╭───────────────────────────────────────────────────────────────────────────╮
│ │
│ @webmasterdevlin/json-server for Deno │
│ │
╰───────────────────────────────────────────────────────────────────────────╯
Usage:
deno run --allow-read --allow-write --allow-net --allow-run mod.ts [options] <source>
Options:
--port, -p Set port [default: 3000]
--host, -H Set host [default: "localhost"]
--routes, -r Path to routes file [string]
--delay, -d Add delay to responses (ms) [number]
--id, -i Set database id field [default: "id"]
--read-only, --ro Allow only GET requests [default: false]
--no-cors, --nc Disable CORS [default: false]
--enable-api-prefix, --api Enable /api/* prefix [default: false]
--quiet, -q Suppress log messages [default: false]
--help, -h Show help [boolean]
--version, -v Show version [boolean]
Examples:
deno run --allow-read --allow-write --allow-net --allow-run mod.ts db.json
deno run --allow-read --allow-write --allow-net --allow-run mod.ts db.json --port 3001
deno run --allow-read --allow-write --allow-net --allow-run mod.ts db.json --delay 500
deno run --allow-read --allow-write --allow-net --allow-run mod.ts db.json --enable-api-prefix
`);
}
/**
* Check if the script is being run directly (not imported as a module)
*/
if (import.meta.main) {
// Parse command line arguments
const args = parse(Deno.args, {
alias: {
p: 'port',
H: 'host',
r: 'routes',
d: 'delay',
i: 'id',
h: 'help',
v: 'version',
q: 'quiet',
nc: 'no-cors',
ro: 'read-only',
api: 'enable-api-prefix',
},
});
// Display help if requested
if (args.help) {
showHelp();
Deno.exit(0);
}
// Display version if requested
if (args.version) {
try {
// Using dynamic import for version information
const packageInfo = await import('npm:@webmasterdevlin/json-server/package.json', {
assert: { type: 'json' },
});
console.log(`@webmasterdevlin/json-server v${packageInfo.default.version}`);
} catch (error) {
console.log('Version information not available');
}
Deno.exit(0);
}
// Get source file (database)
const source = args._.length > 0 ? String(args._[0]) : null;
if (!source) {
console.error('Error: No database source provided');
showHelp();
Deno.exit(1);
}
// Check if source file exists
try {
await Deno.stat(source);
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
console.error(`Error: Database file not found: ${source}`);
Deno.exit(1);
} else if (!(source.startsWith('http://') || source.startsWith('https://'))) {
console.error(`Error accessing database file: ${error.message}`);
Deno.exit(1);
}
}
// Set up server options
const options: ServerOptions = {
port: args.port || 3000,
host: args.host || 'localhost',
cors: !args['no-cors'],
static: [],
middlewares: [],
bodyParser: true,
noCors: args['no-cors'] || false,
noGzip: false,
delay: args.delay || 0,
quiet: args.quiet || false,
readOnly: args['read-only'] || false,
enableApiPrefix: args['enable-api-prefix'] || false,
};
try {
// Create and configure server
const server = create(options);
// Set ID field if specified
if (args.id) {
server.setIdField(args.id);
}
// Load routes if specified
if (args.routes) {
try {
server.loadRoutes(args.routes);
} catch (error) {
console.warn(`Warning: Failed to load routes: ${error.message}`);
}
}
// Load database and start server
server.loadDatabase(source);
await server.start();
// Handle process termination
Deno.addSignalListener('SIGINT', () => {
console.log('\nShutting down...');
Deno.exit(0);
});
} catch (error) {
console.error(`Failed to start server: ${error.message}`);
Deno.exit(1);
}
}
// Export all components for programmatic usage
export * from 'npm:@webmasterdevlin/json-server';