-
-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
Copy pathbin.ts
234 lines (212 loc) · 5.55 KB
/
bin.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { extname } from 'node:path'
import { parseArgs } from 'node:util'
import chalk from 'chalk'
import { watch } from 'chokidar'
import JSON5 from 'json5'
import { Adapter, Low } from 'lowdb'
import { DataFile, JSONFile } from 'lowdb/node'
import { PackageJson } from 'type-fest'
import { fileURLToPath } from 'node:url'
import { createApp } from './app.js'
import { Observer } from './observer.js'
import { Data } from './service.js'
function help() {
console.log(`Usage: json-server [options] <file>
Options:
-p, --port <port> Port (default: 3000)
-h, --host <host> Host (default: localhost)
-s, --static <dir> Static files directory (multiple allowed)
--chunk <size> Server-sent events chunk size (default: 2)
--help Show this message
--version Show version number
`)
}
// Parse args
function args(): {
file: string
port: number
host: string
static: string[]
chunk: number
} {
try {
const { values, positionals } = parseArgs({
options: {
port: {
type: 'string',
short: 'p',
default: process.env['PORT'] ?? '3000',
},
host: {
type: 'string',
short: 'h',
default: process.env['HOST'] ?? 'localhost',
},
static: {
type: 'string',
short: 's',
multiple: true,
default: [],
},
chunk: {
type: 'string',
default: '2'
},
help: {
type: 'boolean',
},
version: {
type: 'boolean',
},
// Deprecated
watch: {
type: 'boolean',
short: 'w',
},
},
allowPositionals: true,
})
// --version
if (values.version) {
const pkg = JSON.parse(
readFileSync(
fileURLToPath(new URL('../package.json', import.meta.url)),
'utf-8',
),
) as PackageJson
console.log(pkg.version)
process.exit()
}
// Handle --watch
if (values.watch) {
console.log(
chalk.yellow(
'--watch/-w can be omitted, JSON Server 1+ watches for file changes by default',
),
)
}
if (values.help || positionals.length === 0) {
help()
process.exit()
}
// App args and options
return {
file: positionals[0] ?? '',
port: parseInt(values.port as string),
host: values.host as string,
static: values.static as string[],
chunk: parseInt(values.chunk as string),
}
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
console.log(chalk.red((e as NodeJS.ErrnoException).message.split('.')[0]))
help()
process.exit(1)
} else {
throw e
}
}
}
const { file, port, host, static: staticArr, chunk } = args()
if (!existsSync(file)) {
console.log(chalk.red(`File ${file} not found`))
process.exit(1)
}
// Handle empty string JSON file
if (readFileSync(file, 'utf-8').trim() === '') {
writeFileSync(file, '{}')
}
// Set up database
let adapter: Adapter<Data>
if (extname(file) === '.json5') {
adapter = new DataFile<Data>(file, {
parse: JSON5.parse,
stringify: JSON5.stringify,
})
} else {
adapter = new JSONFile<Data>(file)
}
const observer = new Observer(adapter)
const db = new Low<Data>(observer, {})
await db.read()
// Create app
const app = createApp(db, { logger: false, static: staticArr, chunk })
function logRoutes(data: Data) {
console.log(chalk.bold('Endpoints:'))
if (Object.keys(data).length === 0) {
console.log(
chalk.gray(`No endpoints found, try adding some data to ${file}`),
)
return
}
console.log(
Object.keys(data)
.map(
(key) => `${chalk.gray(`http://${host}:${port}/`)}${chalk.blue(key)}`,
)
.join('\n'),
)
}
const kaomojis = ['♡⸜(˶˃ ᵕ ˂˶)⸝♡', '♡( ◡‿◡ )', '( ˶ˆ ᗜ ˆ˵ )', '(˶ᵔ ᵕ ᵔ˶)']
function randomItem(items: string[]): string {
const index = Math.floor(Math.random() * items.length)
return items.at(index) ?? ''
}
app.listen(port, () => {
console.log(
[
chalk.bold(`JSON Server started on PORT :${port}`),
chalk.gray('Press CTRL-C to stop'),
chalk.gray(`Watching ${file}...`),
'',
chalk.magenta(randomItem(kaomojis)),
'',
chalk.bold('Index:'),
chalk.gray(`http://localhost:${port}/`),
'',
chalk.bold('Static files:'),
chalk.gray('Serving ./public directory if it exists'),
'',
].join('\n'),
)
logRoutes(db.data)
})
// Watch file for changes
if (process.env['NODE_ENV'] !== 'production') {
let writing = false // true if the file is being written to by the app
let prevEndpoints = ''
observer.onWriteStart = () => {
writing = true
}
observer.onWriteEnd = () => {
writing = false
}
observer.onReadStart = () => {
prevEndpoints = JSON.stringify(Object.keys(db.data).sort())
}
observer.onReadEnd = (data) => {
if (data === null) {
return
}
const nextEndpoints = JSON.stringify(Object.keys(data).sort())
if (prevEndpoints !== nextEndpoints) {
console.log()
logRoutes(data)
}
}
watch(file).on('change', () => {
// Do no reload if the file is being written to by the app
if (!writing) {
db.read().catch((e) => {
if (e instanceof SyntaxError) {
return console.log(
chalk.red(['', `Error parsing ${file}`, e.message].join('\n')),
)
}
console.log(e)
})
}
})
}