json-server 0.17.4 → 1.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,633 +1,112 @@
1
- # JSON Server [![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg?branch=master)](https://github.com/typicode/json-server/actions/workflows/node.js.yml)
2
-
3
- Get a full fake REST API with __zero coding__ in __less than 30 seconds__ (seriously)
4
-
5
- Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
1
+ # json-server
6
2
 
7
- * [Egghead.io free video tutorial - Creating demo APIs with json-server](https://egghead.io/lessons/nodejs-creating-demo-apis-with-json-server)
8
- * [JSONPlaceholder - Live running version](https://jsonplaceholder.typicode.com)
9
- * [__My JSON Server__ - no installation required, use your own data](https://my-json-server.typicode.com)
3
+ [![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg)](https://github.com/typicode/json-server/actions/workflows/node.js.yml)
10
4
 
11
- See also:
12
- * :dog: [husky - Git hooks made easy](https://github.com/typicode/husky)
13
- * :owl: [lowdb - local JSON database](https://github.com/typicode/lowdb)
14
- * ✅ [xv - a beautifully simple and capable test runner](https://github.com/typicode/xv)
5
+ ## Usage
15
6
 
16
- <p>&nbsp;</p>
7
+ Install `json-server`
17
8
 
18
- <h2 align="center">Gold sponsors 🥇</h2>
19
-
20
- <p>&nbsp;</p>
21
-
22
- <p align="center">
23
- <a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=typicode" target="_blank">
24
- <img src="https://i.imgur.com/IBItATn.png" height="70px">
25
- </a>
26
- </p>
27
-
28
- <p>&nbsp;</p>
29
-
30
- <p align="center">
31
- <a href="https://mockend.com/" target="_blank">
32
- <img src="https://jsonplaceholder.typicode.com/mockend.svg" height="70px">
33
- </a>
34
- </p>
35
-
36
- <p>&nbsp;</p>
37
-
38
- <p>&nbsp;</p>
39
-
40
- <h2 align="center">Silver sponsors 🥈</h2>
41
-
42
- <p>&nbsp;</p>
43
-
44
- <p align="center">
45
- <a href="https://cased.com" target="_blank">
46
- <img src="https://user-images.githubusercontent.com/5502029/194441951-b7dca49d-efd6-496d-900b-288004717f11.png" height="55px">
47
- </a>
48
- </p>
49
-
50
- <p>&nbsp;</p>
51
-
52
- <p>&nbsp;</p>
53
-
54
- [Become a sponsor and have your company logo here](https://github.com/users/typicode/sponsorship)
55
-
56
- ## Sponsor
57
-
58
- __Please help me build OSS__ 👉 [GitHub Sponsors](https://github.com/sponsors/typicode) :heart:
59
-
60
- ## Table of contents
61
-
62
- <!-- toc -->
63
-
64
- - [Getting started](#getting-started)
65
- - [Routes](#routes)
66
- * [Plural routes](#plural-routes)
67
- * [Singular routes](#singular-routes)
68
- * [Filter](#filter)
69
- * [Paginate](#paginate)
70
- * [Sort](#sort)
71
- * [Slice](#slice)
72
- * [Operators](#operators)
73
- * [Full-text search](#full-text-search)
74
- * [Relationships](#relationships)
75
- * [Database](#database)
76
- * [Homepage](#homepage)
77
- - [Extras](#extras)
78
- * [Static file server](#static-file-server)
79
- * [Alternative port](#alternative-port)
80
- * [Access from anywhere](#access-from-anywhere)
81
- * [Remote schema](#remote-schema)
82
- * [Generate random data](#generate-random-data)
83
- * [HTTPS](#https)
84
- * [Add custom routes](#add-custom-routes)
85
- * [Add middlewares](#add-middlewares)
86
- * [CLI usage](#cli-usage)
87
- * [Module](#module)
88
- + [Simple example](#simple-example)
89
- + [Custom routes example](#custom-routes-example)
90
- + [Access control example](#access-control-example)
91
- + [Custom output example](#custom-output-example)
92
- + [Rewriter example](#rewriter-example)
93
- + [Mounting JSON Server on another endpoint example](#mounting-json-server-on-another-endpoint-example)
94
- + [API](#api)
95
- * [Deployment](#deployment)
96
- - [Links](#links)
97
- * [Video](#video)
98
- * [Articles](#articles)
99
- * [Third-party tools](#third-party-tools)
100
- - [License](#license)
101
-
102
- <!-- tocstop -->
103
-
104
- ## Getting started
105
-
106
- Install JSON Server
107
-
108
- ```
109
- npm install -g json-server
9
+ ```shell
10
+ npm install json-server
110
11
  ```
111
12
 
112
- Create a `db.json` file with some data
13
+ Create a `db.json` file or run `json-server db.json` to create one with some default resources
113
14
 
114
15
  ```json
115
16
  {
116
17
  "posts": [
117
- { "id": 1, "title": "json-server", "author": "typicode" }
18
+ { "id": "1", "title": "string" },
19
+ { "id": "2", "title": "some post" }
118
20
  ],
119
21
  "comments": [
120
- { "id": 1, "body": "some comment", "postId": 1 }
121
- ],
122
- "profile": { "name": "typicode" }
22
+ { "id": "1", "text": "some text", "postId": "1" },
23
+ { "id": "2", "text": "some text", "postId": "1" }
24
+ ]
123
25
  }
124
26
  ```
125
27
 
126
- Start JSON Server
127
-
128
- ```bash
129
- json-server --watch db.json
130
- ```
131
-
132
- Now if you go to [http://localhost:3000/posts/1](http://localhost:3000/posts/1), you'll get
133
-
134
- ```json
135
- { "id": 1, "title": "json-server", "author": "typicode" }
28
+ ```shell
29
+ json-server db.json
136
30
  ```
137
31
 
138
- Also when doing requests, it's good to know that:
139
-
140
- - If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to `db.json` using [lowdb](https://github.com/typicode/lowdb).
141
- - Your request body JSON should be object enclosed, just like the GET output. (for example `{"name": "Foobar"}`)
142
- - Id values are not mutable. Any `id` value in the body of your PUT or PATCH request will be ignored. Only a value set in a POST request will be respected, but only if not already taken.
143
- - A POST, PUT or PATCH request should include a `Content-Type: application/json` header to use the JSON in the request body. Otherwise it will return a 2XX status code, but without changes being made to the data.
32
+ Run `json-server --help` for a list of options
144
33
 
145
34
  ## Routes
146
35
 
147
- Based on the previous `db.json` file, here are all the default routes. You can also add [other routes](#add-custom-routes) using `--routes`.
148
-
149
- ### Plural routes
150
-
151
36
  ```
152
37
  GET /posts
153
- GET /posts/1
38
+ GET /posts/:id
154
39
  POST /posts
155
- PUT /posts/1
156
- PATCH /posts/1
157
- DELETE /posts/1
158
- ```
159
-
160
- ### Singular routes
161
-
162
- ```
163
- GET /profile
164
- POST /profile
165
- PUT /profile
166
- PATCH /profile
167
- ```
168
-
169
- ### Filter
170
-
171
- Use `.` to access deep properties
172
-
173
- ```
174
- GET /posts?title=json-server&author=typicode
175
- GET /posts?id=1&id=2
176
- GET /comments?author.name=typicode
177
- ```
178
-
179
- ### Paginate
180
-
181
- Use `_page` and optionally `_limit` to paginate returned data.
182
-
183
- In the `Link` header you'll get `first`, `prev`, `next` and `last` links.
184
-
185
-
186
- ```
187
- GET /posts?_page=7
188
- GET /posts?_page=7&_limit=20
189
- ```
190
-
191
- _10 items are returned by default_
192
-
193
- ### Sort
194
-
195
- Add `_sort` and `_order` (ascending order by default)
196
-
197
- ```
198
- GET /posts?_sort=views&_order=asc
199
- GET /posts/1/comments?_sort=votes&_order=asc
200
- ```
201
-
202
- For multiple fields, use the following format:
203
-
204
- ```
205
- GET /posts?_sort=user,views&_order=desc,asc
206
- ```
207
-
208
- ### Slice
209
-
210
- Add `_start` and `_end` or `_limit` (an `X-Total-Count` header is included in the response)
211
-
212
- ```
213
- GET /posts?_start=20&_end=30
214
- GET /posts/1/comments?_start=20&_end=30
215
- GET /posts/1/comments?_start=20&_limit=10
216
- ```
217
-
218
- _Works exactly as [Array.slice](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) (i.e. `_start` is inclusive and `_end` exclusive)_
219
-
220
- ### Operators
221
-
222
- Add `_gte` or `_lte` for getting a range
223
-
224
- ```
225
- GET /posts?views_gte=10&views_lte=20
226
- ```
227
-
228
- Add `_ne` to exclude a value
229
-
230
- ```
231
- GET /posts?id_ne=1
232
- ```
233
-
234
- Add `_like` to filter (RegExp supported)
235
-
236
- ```
237
- GET /posts?title_like=server
238
- ```
239
-
240
- ### Full-text search
241
-
242
- Add `q`
243
-
244
- ```
245
- GET /posts?q=internet
246
- ```
247
-
248
- ### Relationships
249
-
250
- To include children resources, add `_embed`
251
-
252
- ```
253
- GET /posts?_embed=comments
254
- GET /posts/1?_embed=comments
255
- ```
256
-
257
- To include parent resource, add `_expand`
258
-
259
- ```
260
- GET /comments?_expand=post
261
- GET /comments/1?_expand=post
262
- ```
263
-
264
- To get or create nested resources (by default one level, [add custom routes](#add-custom-routes) for more)
265
-
266
- ```
267
- GET /posts/1/comments
268
- POST /posts/1/comments
269
- ```
270
-
271
- ### Database
272
-
40
+ PUT /posts
41
+ DELETE /posts/:id
273
42
  ```
274
- GET /db
275
- ```
276
-
277
- ### Homepage
278
43
 
279
- Returns default index file or serves `./public` directory
280
-
281
- ```
282
- GET /
283
- ```
44
+ ## Params
284
45
 
285
- ## Extras
46
+ ### Comparison
286
47
 
287
- ### Static file server
48
+ - ` ` →`==`
49
+ - `lt` → `<`
50
+ - `lte` → `<=`
51
+ - `gt` → `>`
52
+ - `gte` → `>=`
53
+ - `ne` → `!=`
288
54
 
289
- You can use JSON Server to serve your HTML, JS and CSS, simply create a `./public` directory
290
- or use `--static` to set a different static files directory.
291
-
292
- ```bash
293
- mkdir public
294
- echo 'hello world' > public/index.html
295
- json-server db.json
296
55
  ```
297
-
298
- ```bash
299
- json-server db.json --static ./some-other-dir
56
+ GET /posts?views_gt=9000
300
57
  ```
301
58
 
302
- ### Alternative port
59
+ ### Range
303
60
 
304
- You can start JSON Server on other ports with the `--port` flag:
61
+ - `start`
62
+ - `end`
63
+ - `limit`
305
64
 
306
- ```bash
307
- $ json-server --watch db.json --port 3004
308
65
  ```
309
-
310
- ### Access from anywhere
311
-
312
- You can access your fake API from anywhere using CORS and JSONP.
313
-
314
- ### Remote schema
315
-
316
- You can load remote schemas.
317
-
318
- ```bash
319
- $ json-server http://example.com/file.json
320
- $ json-server http://jsonplaceholder.typicode.com/db
66
+ GET /posts?_start=10&_end=20
67
+ GET /posts?_start=10&_limit=10
321
68
  ```
322
69
 
323
- ### Generate random data
70
+ ### Paginate
324
71
 
325
- Using JS instead of a JSON file, you can create data programmatically.
72
+ - `page`
73
+ - `per_page` (default = 10)
326
74
 
327
- ```javascript
328
- // index.js
329
- module.exports = () => {
330
- const data = { users: [] }
331
- // Create 1000 users
332
- for (let i = 0; i < 1000; i++) {
333
- data.users.push({ id: i, name: `user${i}` })
334
- }
335
- return data
336
- }
337
75
  ```
338
-
339
- ```bash
340
- $ json-server index.js
76
+ GET /posts?_page=1&_per_page=25
341
77
  ```
342
78
 
343
- __Tip__ use modules like [Faker](https://github.com/faker-js/faker), [Casual](https://github.com/boo1ean/casual), [Chance](https://github.com/victorquinn/chancejs) or [JSON Schema Faker](https://github.com/json-schema-faker/json-schema-faker).
344
-
345
- ### HTTPS
346
-
347
- There are many ways to set up SSL in development. One simple way is to use [hotel](https://github.com/typicode/hotel).
348
-
349
- ### Add custom routes
79
+ ### Sort
350
80
 
351
- Create a `routes.json` file. Pay attention to start every route with `/`.
81
+ - `_sort=f1,f2`
352
82
 
353
- ```json
354
- {
355
- "/api/*": "/$1",
356
- "/:resource/:id/show": "/:resource/:id",
357
- "/posts/:category": "/posts?category=:category",
358
- "/articles?id=:id": "/posts/:id"
359
- }
360
83
  ```
361
-
362
- Start JSON Server with `--routes` option.
363
-
364
- ```bash
365
- json-server db.json --routes routes.json
84
+ GET /posts?_sort=id,-views
366
85
  ```
367
86
 
368
- Now you can access resources using additional routes.
87
+ ### Nested fields
369
88
 
370
- ```sh
371
- /api/posts # → /posts
372
- /api/posts/1 # → /posts/1
373
- /posts/1/show # → /posts/1
374
- /posts/javascript # → /posts?category=javascript
375
- /articles?id=1 # → /posts/1
376
- ```
89
+ - `x.y.z`
377
90
 
378
- ### Add middlewares
91
+ ### Include
379
92
 
380
- You can add your middlewares from the CLI using `--middlewares` option:
381
-
382
- ```js
383
- // hello.js
384
- module.exports = (req, res, next) => {
385
- res.header('X-Hello', 'World')
386
- next()
387
- }
388
93
  ```
389
-
390
- ```bash
391
- json-server db.json --middlewares ./hello.js
392
- json-server db.json --middlewares ./first.js ./second.js
94
+ GET /posts?_include=comments
95
+ GET /comments?_include=post
393
96
  ```
394
97
 
395
- ### CLI usage
98
+ ## Delete
396
99
 
397
100
  ```
398
- json-server [options] <source>
399
-
400
- Options:
401
- --config, -c Path to config file [default: "json-server.json"]
402
- --port, -p Set port [default: 3000]
403
- --host, -H Set host [default: "localhost"]
404
- --watch, -w Watch file(s) [boolean]
405
- --routes, -r Path to routes file
406
- --middlewares, -m Paths to middleware files [array]
407
- --static, -s Set static files directory
408
- --read-only, --ro Allow only GET requests [boolean]
409
- --no-cors, --nc Disable Cross-Origin Resource Sharing [boolean]
410
- --no-gzip, --ng Disable GZIP Content-Encoding [boolean]
411
- --snapshots, -S Set snapshots directory [default: "."]
412
- --delay, -d Add delay to responses (ms)
413
- --id, -i Set database id property (e.g. _id) [default: "id"]
414
- --foreignKeySuffix, --fks Set foreign key suffix, (e.g. _id as in post_id)
415
- [default: "Id"]
416
- --quiet, -q Suppress log messages from output [boolean]
417
- --help, -h Show help [boolean]
418
- --version, -v Show version number [boolean]
419
-
420
- Examples:
421
- json-server db.json
422
- json-server file.js
423
- json-server http://example.com/db.json
424
-
425
- https://github.com/typicode/json-server
426
- ```
427
-
428
- You can also set options in a `json-server.json` configuration file.
429
-
430
- ```json
431
- {
432
- "port": 3000
433
- }
101
+ DELETE /posts/1
102
+ DELETE /posts/1?_include=comments
434
103
  ```
435
104
 
436
- ### Module
437
-
438
- If you need to add authentication, validation, or __any behavior__, you can use the project as a module in combination with other Express middlewares.
439
-
440
- #### Simple example
441
-
442
- ```sh
443
- $ npm install json-server --save-dev
444
- ```
105
+ # Serving static files
445
106
 
446
- ```js
447
- // server.js
448
- const jsonServer = require('json-server')
449
- const server = jsonServer.create()
450
- const router = jsonServer.router('db.json')
451
- const middlewares = jsonServer.defaults()
452
-
453
- server.use(middlewares)
454
- server.use(router)
455
- server.listen(3000, () => {
456
- console.log('JSON Server is running')
457
- })
458
- ```
107
+ If you create a `./public` directory, JSON Serve will serve its content in addition to the REST API. You can add custom directories using `-s/--static` option.
459
108
 
460
109
  ```sh
461
- $ node server.js
462
- ```
463
-
464
- The path you provide to the `jsonServer.router` function is relative to the directory from where you launch your node process. If you run the above code from another directory, it’s better to use an absolute path:
465
-
466
- ```js
467
- const path = require('path')
468
- const router = jsonServer.router(path.join(__dirname, 'db.json'))
110
+ json-server -s ./static
111
+ json-server -s ./static -s ./node_modules
469
112
  ```
470
-
471
- For an in-memory database, simply pass an object to `jsonServer.router()`.
472
-
473
- To add custom options (eg. `foreginKeySuffix`) pass in an object as the second argument to `jsonServer.router('db.json', { foreginKeySuffix: '_id' })`.
474
-
475
- Please note also that `jsonServer.router()` can be used in existing Express projects.
476
-
477
- #### Custom routes example
478
-
479
- Let's say you want a route that echoes query parameters and another one that set a timestamp on every resource created.
480
-
481
- ```js
482
- const jsonServer = require('json-server')
483
- const server = jsonServer.create()
484
- const router = jsonServer.router('db.json')
485
- const middlewares = jsonServer.defaults()
486
-
487
- // Set default middlewares (logger, static, cors and no-cache)
488
- server.use(middlewares)
489
-
490
- // Add custom routes before JSON Server router
491
- server.get('/echo', (req, res) => {
492
- res.jsonp(req.query)
493
- })
494
-
495
- // To handle POST, PUT and PATCH you need to use a body-parser
496
- // You can use the one used by JSON Server
497
- server.use(jsonServer.bodyParser)
498
- server.use((req, res, next) => {
499
- if (req.method === 'POST') {
500
- req.body.createdAt = Date.now()
501
- }
502
- // Continue to JSON Server router
503
- next()
504
- })
505
-
506
- // Use default router
507
- server.use(router)
508
- server.listen(3000, () => {
509
- console.log('JSON Server is running')
510
- })
511
- ```
512
-
513
- #### Access control example
514
-
515
- ```js
516
- const jsonServer = require('json-server')
517
- const server = jsonServer.create()
518
- const router = jsonServer.router('db.json')
519
- const middlewares = jsonServer.defaults()
520
-
521
- server.use(middlewares)
522
- server.use((req, res, next) => {
523
- if (isAuthorized(req)) { // add your authorization logic here
524
- next() // continue to JSON Server router
525
- } else {
526
- res.sendStatus(401)
527
- }
528
- })
529
- server.use(router)
530
- server.listen(3000, () => {
531
- console.log('JSON Server is running')
532
- })
533
- ```
534
- #### Custom output example
535
-
536
- To modify responses, overwrite `router.render` method:
537
-
538
- ```javascript
539
- // In this example, returned resources will be wrapped in a body property
540
- router.render = (req, res) => {
541
- res.jsonp({
542
- body: res.locals.data
543
- })
544
- }
545
- ```
546
-
547
- You can set your own status code for the response:
548
-
549
-
550
- ```javascript
551
- // In this example we simulate a server side error response
552
- router.render = (req, res) => {
553
- res.status(500).jsonp({
554
- error: "error message here"
555
- })
556
- }
557
- ```
558
-
559
- #### Rewriter example
560
-
561
- To add rewrite rules, use `jsonServer.rewriter()`:
562
-
563
- ```javascript
564
- // Add this before server.use(router)
565
- server.use(jsonServer.rewriter({
566
- '/api/*': '/$1',
567
- '/blog/:resource/:id/show': '/:resource/:id'
568
- }))
569
- ```
570
-
571
- #### Mounting JSON Server on another endpoint example
572
-
573
- Alternatively, you can also mount the router on `/api`.
574
-
575
- ```javascript
576
- server.use('/api', router)
577
- ```
578
-
579
- #### API
580
-
581
- __`jsonServer.create()`__
582
-
583
- Returns an Express server.
584
-
585
- __`jsonServer.defaults([options])`__
586
-
587
- Returns middlewares used by JSON Server.
588
-
589
- * options
590
- * `static` path to static files
591
- * `logger` enable logger middleware (default: true)
592
- * `bodyParser` enable body-parser middleware (default: true)
593
- * `noCors` disable CORS (default: false)
594
- * `readOnly` accept only GET requests (default: false)
595
-
596
- __`jsonServer.router([path|object], [options])`__
597
-
598
- Returns JSON Server router.
599
-
600
- * options (see [CLI usage](#cli-usage))
601
-
602
- ### Deployment
603
-
604
- You can deploy JSON Server. For example, [JSONPlaceholder](http://jsonplaceholder.typicode.com) is an online fake API powered by JSON Server and running on Heroku.
605
-
606
- ## Links
607
-
608
- ### Video
609
-
610
- * [Creating Demo APIs with json-server on egghead.io](https://egghead.io/lessons/nodejs-creating-demo-apis-with-json-server)
611
-
612
- ### Articles
613
-
614
- * [Node Module Of The Week - json-server](http://nmotw.in/json-server/)
615
- * [ng-admin: Add an AngularJS admin GUI to any RESTful API](http://marmelab.com/blog/2014/09/15/easy-backend-for-your-restful-api.html)
616
- * [Fast prototyping using Restangular and Json-server](https://glebbahmutov.com/blog/fast-prototyping-restangular-and-json-server/)
617
- * [Create a Mock REST API in Seconds for Prototyping your Frontend](https://coligo.io/create-mock-rest-api-with-json-server/)
618
- * [No API? No Problem! Rapid Development via Mock APIs](https://medium.com/@housecor/rapid-development-via-mock-apis-e559087be066#.93d7w8oro)
619
- * [Zero Code REST With json-server](https://dzone.com/articles/zero-code-rest-with-json-server)
620
-
621
- ### Third-party tools
622
-
623
- * [Grunt JSON Server](https://github.com/tfiwm/grunt-json-server)
624
- * [Docker JSON Server](https://github.com/clue/docker-json-server)
625
- * [JSON Server GUI](https://github.com/naholyr/json-server-gui)
626
- * [JSON file generator](https://github.com/dfsq/json-server-init)
627
- * [JSON Server extension](https://github.com/maty21/json-server-extension)
628
-
629
- ## License
630
-
631
- MIT
632
-
633
- [Supporters](https://thanks.typicode.com) ✨
package/lib/app.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { App } from '@tinyhttp/app';
2
+ import { Low } from 'lowdb';
3
+ import { Data } from './service.js';
4
+ export type AppOptions = {
5
+ logger?: boolean;
6
+ static?: string[];
7
+ };
8
+ export declare function createApp(db: Low<Data>, options?: AppOptions): App<import("@tinyhttp/app").Request, import("@tinyhttp/app").Response<unknown>>;