首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Github上基于lodash和lowdb json查询服务器json-server

Github上基于lodash和lowdb json查询服务器json-server

原创
作者头像
MiaoGIS
修改2019-03-04 14:59:48
1.8K0
修改2019-03-04 14:59:48
举报
文章被收录于专栏:Python in AI-IOTPython in AI-IOT

Github上基于lodash和lowdb json查询服务器json-server

* [Plural routes]多层路由

* [Singular routes]单路由

* [Filter]过滤

* [Paginate]分页

* [Sort]排序

* [Slice]切片

* [Operators]比较运算

* [Full-text search]全文检索

* [Relationships]关联

* [Database]数据库

- [Extras]扩展

* [Static file server]静态文件服务器

* [Alternative port]配置端口

* [Access from anywhere]跨域

* [Remote schema]第三方数据

* [Generate random data]生成随机数据

* [HTTPS]HTTPS

* [Add custom routes]自定义路由

* [Add middlewares]中间件

安装 JSON Server

```

npm install -g json-server

```

建立一个 `db.json` 文件

json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
} 

开启服务

```bash

json-server --watch db.json

```

打开浏览器 [http://localhost:3000/posts/1](http://localhost:3000/posts/1), 返回json数据

{ "id": 1, "title": "json-server", "author": "typicode" } 

多层路由

GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

单路由

GET    /profile
POST   /profile
PUT    /profile
PATCH  /profile

过滤

使用 `.` 来获得嵌套属性

GET /posts?title=json-server&author=typicode
GET /posts?id=1&id=2
GET /comments?author.name=typicode

分页

使用 `_page` 和 `_limit` 返回分页数据

在响应返回头信息 `Link` 中可以拿到 `first`, `prev`, `next` and `last` 链接

GET /posts?_page=7
GET /posts?_page=7&_limit=20

默认返回10条数据

排序

`_sort` 和 `_order` (默认升序)

GET /posts?_sort=views&_order=asc
GET /posts/1/comments?_sort=votes&_order=asc

多个字段排序使用:

GET /posts?_sort=user,views&_order=desc,asc

切片

`_start` , `_end` 和 `_limit` (响应头部包含 `X-Total-Count` )

GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=20&_end=30
GET /posts/1/comments?_start=20&_limit=10

和 [Array.slice]作用一样

比较操作

使用 `_gte` 或 `_lte` 来得到范围内数据

GET /posts?views_gte=10&views_lte=20

用 `_ne` 来排除某一项得到其他数据

GET /posts?id_ne=1

使用 `_like` 过滤 (支持正则表达式)

GET /posts?title_like=server

全文检索

使用 `q`

GET /posts?q=internet

关联

关联子节点数据, 使用 `_embed`

GET /posts?_embed=comments
GET /posts/1?_embed=comments

包含父节点,使用 `_expand`

GET /comments?_expand=post
GET /comments/1?_expand=post

使用数据库

GET /db

首页

默认返回 index 文件或者使用 `./public` 文件夹

GET /

扩展

静态文件服务器

通过创建 `./public` 目录,使用 JSON Server 来返回 HTML, JS and CSS,

或者使用 `--static` 设置静态文件目录.

json-server db.json
json-server db.json --static ./some-other-di

JSON Server 使用 `--port` 配置端口:

json-server --watch db.json --port 3004 

跨域访问

支持 CORS and JSONP.

第三方数据

加载第三方数据

 json-server http://example.com/file.json
 json-server http://jsonplaceholder.typicode.com/db

生成随机数据

使用js文件来通过程序生成数据

// index.js
module.exports = () => {
  const data = { users: [] }
  // Create 1000 users
  for (let i = 0; i < 1000; i++) {
    data.users.push({ id: i, name: `user${i}` })
  }
  return data
}
json-server index.js

使用 像 [Faker]模块方便生成随机数据

HTTPS

许多在开发中使用 SSL 的方式. 比如 [hotel](https://github.com/typicode/hotel).

自定义路由

创建 `routes.json` 文件. 注意每个路由使用 `/`开始.

{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id",
  "/posts/:category": "/posts?category=:category",
  "/articles\\?id=:id": "/posts/:id"
}

使用`--routes` 选项启动 JSON Server .

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

中间件

通过 CLI 的 `--middlewares`选项来加入中间件:

// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
  next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

CLI 使用

json-server [options] <source>

Options:

--config, -c 配置文件 [default: "json-server.json"]

--port, -p 设置端口 [default: 3000]

--host, -H 设置host [default: "localhost"]

--watch, -w 监视文件内容变化 [boolean]

--routes, -r 路由文件

--middlewares, -m 一个或多个中间件文件 [array]

--static, -s 静态文件目录

--read-only, --ro 只允许get方法 [boolean]

--no-cors, --nc 禁止 跨域 [boolean]

--no-gzip, --ng 禁止 GZIP内容编码 [boolean]

--snapshots, -S 设置快照目录 [default: "."]

--delay, -d 响应延迟 (ms)

--id, -i 设置数据库ID字段 (e.g. _id) [default: "id"]

--foreignKeySuffix, --fks 设置外键后缀, (e.g. _id as in post_id) [default: "Id"]

--quiet, -q 禁止日志 [boolean]

--help, -h 显示帮助 [boolean]

--version, -v 显示版本号 [boolean]

示例

json-server db.json

json-server file.js

json-server http://example.com/db.json

也可以使用`json-server.json` 配置文件配置选项.

json
{
  "port": 3000
}

模块

如果你需要使用授权,验证或其他特性,你可以把它当作模块组合Express的其他中间件实现。

示例

npm install json-server --save-dev
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})
node server.js

提供给 `jsonServer.router`函数的路径是相对于启动node目录的路径. 如果你在别的目录下运行上面代码, 最好使用绝对路径:

const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json')) 

对于内存数据库, 简单传递 `jsonServer.router()`一个对象.

注意 `jsonServer.router()`也可以用在现有的Express项目中.

自定义路由示例

假如你需要一个响应查询参数的路由,或者另一个需要在每个资源上加上时间戳。

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)
// Add custom routes before JSON Server route
server.get('/echo', (req, res) => {
  res.jsonp(req.query)
})
// To handle POST, PUT and PATCH you need to use a body-parse
// You can use the one used by JSON Serve
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now()
  }
  // Continue to JSON Server route
  next()
})
// Use default route
server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
}) 

访问控制

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)
server.use((req, res, next) => {
 if (isAuthorized(req)) { // add your authorization logic here
   next() // continue to JSON Server route
 } else {
   res.sendStatus(401)
 }
})
server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})

自定义输出

要修改响应信息, 需要重载 `router.render` 方法:

// In this example, returned resources will be wrapped in a body property
router.render = (req, res) => {
  res.jsonp({
    body: res.locals.data
  })
}

你可以在响应上添加自己的状态码:

// In this example we simulate a server side error response
router.render = (req, res) => {
  res.status(500).jsonp({
    error: "error message here"
  })
}

重定向

添加重定向规则, 使用 `jsonServer.rewriter()`:

// Add this before server.use(router)
server.use(jsonServer.rewriter({
  '/api/*': '/$1',
  '/blog/:resource/:id/show': '/:resource/:id'
}))

在别的节点挂载Json Server

你可以在 `/api`上挂载路由.

server.use('/api', router)

API

__`jsonServer.create()`__

返回 Express server.

__`jsonServer.defaults([options])`__

返回JSON Server使用的中间件 .

* 选项

* `static` 静态文件目录

* `logger` 允许给中间件添加日志 (默认: true)

* `bodyParser` 允许解析中间件 (默认: true)

* `noCors` 禁止 CORS (默认: false)

* `readOnly` 只接受GET请求(默认: false)

__`jsonServer.router([path|object])`__

返回 JSON Server 路由.

jsonServer.pptx

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 扩展
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档