background
We didn’t use mock service in our previous projects. We waited for the backend to give interface fields or left empty bits in the front end. However, the project of the new company needs to build a mock service. I wanted to move the JSON-server of the old project, but I found that adding a mock API was too complicated. The mock service should be simple, so I decided to write one myself (I thought it would be good to write a JSON file…). .
Anticipatory design
As I understand mock services, I simply check that restful urls return the corresponding data, and then take a quick look at the documentation example
1. Create db.json
{
"posts": [{"id": 1."title": "json-server"."author": "typicode"}]."comments": [{"id": 1."body": "some comment"."postId": 1}]."profile": { "name": "typicode"}}Copy the code
2, start,
$ json-server –watch db.json
3, visit http://localhost:3000/posts/1
{ "id": 1."title": "json-server"."author": "typicode" }
Copy the code
Wow isn’t that easy (burrow for yourself), then just transform the data into a routing form
// db.js
module.expors = {
'/posts': require('./data/posts.json'),
'/user/login': require('./data/user/login.json'),
'/user/logout': require('./data/user/logout.json')}Copy the code
The directory structure
Mock | └ ─ ─ ─ data | | | └ ─ ─ ─ posts. The json | └ ─ ─ ─ the user | | | └ ─ ─ ─ the login. The json | └ ─ ─ ─ logout. Json | └ ─ ─ ─ the js └ ─ ─ ─ for server by js / / expected The node server. JsCopy the code
Practice a
Write server. Js
const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)
// Get db data
const db = require('./db.js')
// Use router
server.use(jsonServer.router(db))
server.listen(3000, () = > {console.log('JSON Server is running on 3000')})Copy the code
An error occurred after executing Node server.js
/ aren't supported, if you want to tweak default routes, see
https://github.com/typicode/json-server/#add-custom-routes
Copy the code
Db data is not supported in routing style, so try to change db data into object nested mode, although it is not intuitive to see the interface address, but at least it is only a JSON file
// db.js
module.expors = {
'posts': require('./data/posts.json'),
'user': {
'login': require('./data/user/login.json'),
'logout': require('./data/user/logout.json')}}Copy the code
This bottom can run, open http://localhost:3000/user/login, showing how is an empty object {}, log shows the GET/user/login 404 ms 4.161-2; Open the http://localhost:3000/user, able to display the data of the login and logout, seems as/user interface, the json – how return/user/login server data? Don’t support routing style, even this can’t read…
practice
Seeing that there is a jsonServer.rewriter method, we can rewrite db.js and server.js again
// db.js
module.expors = {
'posts': require('./data/posts.json'),
'user_login': require('./data/user/login.json'),
'user_logout': require('./data/user/logout.json')}Copy the code
// server.js. Omit some code// It needs to be added before server.use(router)
server.use(jsonServer.rewriter({
'/user/login': '/user_login'.'/user/logout': '/user_logout'
}))
// Use router
server.use(jsonServer.router(db))
server.listen(3000, () = > {console.log('JSON Server is running on 3000')})Copy the code
This finally makes it possible to run the mock service, although it’s a bit ugly, and jSON-server itself only supports /posts/: ID (selected based on the specified ID attribute of the item), /posts/:id/ XXX is not supported.
perfect
Js and jsonServer.rewriter are a hassle to add manually when more and more files are created, so db and jsonServer.rewriter need to be generated automatically from the file directory. So we can add the API just by adding the JSON file in the appropriate path (the address is attached at the end of the code)
confusion
As a front-end use of mock services, in fact, only to solve the development of get request data blank, avoid the need to modify the page before filling data; Another is to write enough intuitive, simple enough, at this point I think jSON-server does not do very well (I hope I do not understand the use of JSON-server), can not intuitively see the routing interface, Does not properly represent restful apis (jsonServer.rewriter needs to be added).
If I were writing a mock service, I would probably use koA and Koa-Router and just write the GET routing interface
// router.js
router.get('/posts', () = >require('./data/posts.json'))
router.get('/posts/:id', () = >require('./data/posts/id.json'))
router.get('/user/login', () = >require('./data/user/login.json'))
router.get('/user/logout', () = >require('./data/user/logout.json'))
Copy the code
I know that jSON-server also has a server.get method, but this seems to conflict with the db.json file
I will write a JSON file for each interface, which at least looks intuitive and is simple enough to write, and my manual implementation of restful is much less clear than jSON-server support;
conclusion
It is my first practice to build jSON-server. I may not be quite right in usage and understanding. I hope you can point out any problems. I have wrapped the mock service into my vue-cli template, which can be installed via vue init masongzhi/vue-template-webpack my-project. The mock service is in /mock folder.
Ps:
Related articles: Customizing vUE – CLI Template/webpack