In the previous article, we introduced the basic usage of JSON-server in detail. Simple add, delete, change and query operations are completed. However, if we need a large amount of reasonable data, the previous operation seems to be useless, or we want to customize the API access address, etc. Then this article is just what you need.

Dynamic data

Generate data dynamically using JS

Create the db.js file

module.exports = function() {
  let data = { list: []}// Create 1000 datas
  for (let i = 0; i < 1000; i++) {
    data.list.push({ id: i, name: 'user' + i,link:'www.'+ i + '.com'})}return data
}
Copy the code

Execute in this directory

json-server db.js
Copy the code

Visit http://localhost:3000/list now will see the dynamically generated 1000 data, the manual to us in the json file write article 1000 data effect, but certainly not so convenient. Fortunately, JSON-server supports jSON-formatted data that is dynamically generated using JS.

Mockjs generates the data

Although we used JS to generate some data dynamically, it didn’t seem very logical. Since we want to simulate, let’s simulate some reasonable data. We recommend Mockjs, a good third-party library for data simulation.

The last article left me with a thought: MockJS could exist as a standalone Mock Server, but why not use it on its own?

  • Cannot be used across domains
  • Conflicts with routing processing logic in some frameworks
  • Unable to define complex data structures
  • Complex routes cannot be customized

In fact, there are many data generators. It must be mentioned here that Faker supports almost all commonly used data formats and has multiple languages. However, as many people on the Internet have said, his Chinese data is based on Western characters and cannot well simulate Chinese.

For example, I randomly generate a user’s information (city, street, company, month, email, phone number) :

It’s clear that the data generated by FAker is really poorly readable, and look at MockJS

let Mock  = require('mockjs');
let Random = Mock.Random;

console.log(Random.city());  
console.log(Random.cname()); 
console.log(Random.date());  
console.log(Mock.mock({      
  "stars|1-10": "★"
}));
console.log(Random.image('200x100'.'#4A7BF7'.'hello'))
Copy the code

It can be seen that the generated data is very readable, and the picture provider is still domestic (no need to climb the ladder to access).

Generate realistic and reasonable data

Install mockJS in the directory where your db.js file is located

npm install mockjs --save
Copy the code

The use of MockJS will not be repeated here; it is documented. Mockjs official website: mockjs.com/

Transform the db. Js

let Mock  = require('mockjs');
let Random = Mock.Random;
module.exports = function() {
  let data = { list: []}// Create 1000 datas
  for (let i = 0; i < 1000; i++) {
    data.list.push({ id: i, name: Random.cname(),link:Random.url() })
  }
  return data
}
Copy the code

You can see the data generated this time

Configuration items

Take a look at the jSON-server configuration items listed in the previous article.

json-server [options] <source> Options: --config, -c specifies the config file."json-server.json"] --port, -p Set port number [default: 3000] --host, -h set host [default:"0.0.0.0"[Boolean] --routes, -r --static,-sSet static files --read-only, --ro only allow GET requests [Boolean] --no-cors, --nc Forbid cross-domain resource sharing [Boolean] --no-gzip, --ng Disable GZIP [Boolean] --snapshots, -s Setting snapshot directories."."]
  --delay, -dSet feedback delay (ms) --id, -i sets the id attribute of data (e.g. _id) [default:"id"[Boolean] --help, -h Display help information [Boolean] --version, -v Display version number [Boolean]Copy the code

Directly on the command line, for example

json-server db.js -d 500 -q -r ./routes.json
Copy the code

You can also create a json-server.json file for configuration

{
    "watch": true."delay": 500."quiet": true."routes": "./routes.json"
}

Copy the code

And then run it directly

json-server db.js
Copy the code

You can also use NPM to boot

Custom Route

Custom routing is commonly referred to as giving the API request address a separate name, and after consultation with the background to avoid the trouble of changing the interface address later.

Create router.json files in the mock directory, noting that each routing file should start with a slash.

{
  "/api": "/list"."/api/list/:id": "/list/:id"."/api/users? name=:name":"/users? name=:name"
}

Copy the code

In this JSON file, the key is the API path to be accessed during real deployment, and the corresponding value is the virtual API path during development. Now accessing/API /list/1 and accessing /list/1 both return the contents of /list/1

Advanced search

The Filter (Filter)

Use. To manipulate object property values, such as accessing deeper properties

GET /list? name.length=2&id=888 GET /list? name.age=18Copy the code

Paginate (paging)

Use _page and optional _limit to customize the returned data (10 are returned by default if not set). In the Response Headers returned, there is a Link attribute that contains first, prev, Next and last links. And then there’s x-total-count

GET /list? name.length=2&id=888 GET /list? name.age=18Copy the code

Sort (Sort)

Use _sort and _order (default: ascending)

GET /list? _sort=id&_order=ascCopy the code

For multi-field sorting, you can do this

GET /list? _sort=id,name.length&_order=desc,ascCopy the code

Slice (separated)

Use _start and _end or _limit

GET /list? _start=2&_end=5 GET /list? _start=10&_limit=5Copy the code

Operators (operation)

Pick a range using _GTE or _LTE

Select id between 2 and 5GET /list? id_gte=2&id_lte=5Copy the code

Exclude a value with _ne

GET /list? Name_ne = wandering soulsCopy the code

Fuzzy lookup with _like (regular expression support)

GET /list? Name_like = wandering soulsCopy the code

Full-text Search

Using q, the object traverses all values to find the data that contains the specified value

GET /list? Q = aCopy the code

Relationships Map

Get data that contains subordinate resources, using _embed

GET /parents? _embed=childrenCopy the code

To get data containing the parent resource, use _expand

GET /children? _expand=parentsCopy the code

There’s a lot more I haven’t talked about, but that’s enough.

Json-server official website: github.com/typicode/js…