js代码技巧

2021/12/4

# md5加密

# 易懂的代码

# map替代switch

  • 大部分业务场景下,map都能够替换switch,写出更优雅的代码

# JSON-server

# JSON-server 的安装和用法

// install
npm install -g json-server

// db.json
{
    "songs":[
      { "id": 1, "name": "Baby"}
    ],
    "comments": [
      { "id": 1, "content": "nice" }
    ]
  }

// start server
json-server --watch db.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

GET http://localhost:3000/songs/1 会返回 { "id":1,"name":"Baby"} 根据songs/1路由1进行筛选 POST、PUT、PATCH、DELETE 操作会改变db.json文件的内容

🍅 Routes 规则-过滤

{
  "songs": [
    { "name": "吻别", "artist": "张学友" },
    { "name": "燃烧我的卡路里 ", "artist": "火箭少女 101" },
    { "name": "麻雀", "artist": "李荣浩" }
  ],
  "comments": [
      { "id": 1, "content": "nice" }
    ]
}
GET /songs?artist=张学友
GET /songs?artist=张学友&arttist=李荣浩
GET /comments?author.id=1
1
2
3
4
5
6
7
8
9
10
11
12
13

🍅 Routes 规则-翻页与排序

// 以_开头的是json-server的保留字
// 分页
GET /songs?_page=2
GET /songs?_page=1&_limit=15

// 排序
GET /songs?_sort=id&_order=asc

// 多字段排序
GET /songs/_sort=id,name&_order=desc,asc
1
2
3
4
5
6
7
8
9
10

🍅 Routes 规则-查询

// operators:
// _gte _lte _ne 大约小于等于
GET /users?age_gte=10&age_lte=20 
GET /users?age_ne=18

// _like 支持正则
GET /songs?name_like=// q 全局搜索
GET /songs?q=喜欢
1
2
3
4
5
6
7
8
9
10

🍅 自定义 routes

  • 更贴近后端接口
// routes.json
// 左边是实际访问的路径,右边是资源的路径
{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id", 
  "/posts/:category": "/posts?category=:cagegory",
  "/articles\\?id=:id": "/posts/:id"
}

// 添加启动参数:json-server db.json --routes routes.json
/api/posts // -> /posts
/api/posts/1  // -> /posts/1
/posts/1/show //  -> /posts/1
/posts/javascript // -> posts?category=javascript
/articles?id=1 // -> /posts/1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

🍅 添加 middleware

  • 统一定制个性化请求
// my-middleware.js
module.exports= (req, res ,next) => {
  res.header('X-token',"xxxxx")
  next()
}
// 启动
json-server db.json --middlewares ./my-middleware.js
1
2
3
4
5
6
7

# Mock.js生成随机数据

当数据量过大时候,我们不能手写庞大数据量的db.json,json-server也支持js对象。

快速生成随机数据-Mock.js

// index.js
const Mock = require('mock.js')
module.exports= () => {
  const data = Mock.mock({
    'user|1000': [{{
      'id|+1': 1,
      'name': '@first @last'
    }]
  })
  return data
}
// 启动
json-server index.js --middlewares ./my-middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13

# JSON-Server的基本使用

搭配Mock.js 生成随机数据接口

🍅 查询歌单列表

新建文件index.js

const Mock = require('mockjs')

module.exports= ()=> {
    const data = Mock.mock({
        'playlists|100': [{
            'id|+1':1,
            'name': '@title',
            'cover': '@image'
        }]
    })
    return data
}
1
2
3
4
5
6
7
8
9
10
11
12

新建routes.json

// /api/music/ 下面所有的请求转发到去掉这个前缀的下面
// $1 表示任意的字符
{
    "/api/music/*": "/$1"
}
1
2
3
4
5

启动 json-server index.js --routes routes.json

访问 http://localhost:3000/api/music/playlists可以获得100条数据

🍅 查询分页的歌单

修改routes.json

{
    "/api/music/*": "/$1",
    "/playlists\\?limit=:limit&offset=:offset": "/playlists?_start=:offset&_limit=:limit"
}
1
2
3
4

启动 json-server index.js --routes routes.json

访问 http://localhost:3000/api/music/playlists?limit=10&offset=20从20开始返回10条数据

🍅 新增一个歌单

// 用curl模拟一下请求 参数{"name":"夜曲","cover":"xxxx"}
curl localhost:3000/api/music/playlists -X POST -d '{"name":"夜曲","cover":"xxxx"}' -H 'Content-Type: application/json'
1
2

🍅 修改一个歌单

curl localhost:3000/api/music/playlists/101 -X PUT -d '{"id":101,"name":"月半小夜曲","cover":"xxxx"}' -H 'Content-Type: application/json'
1

🍅 删除一个歌单

curl localhost:3000/api/music/playlists/101 -X DELETE  -H 'Content-Type: application/json'
1

以上也可以用postman模拟请求

# 给所有的响应头添加header

新建middleware.js

json-server index.js --routes routes.json --middleware middleware.js
1
上次更新: 9/17/2024