api-分类管理-创建分类
api 设计
基本信息
Path: /category/create/:userId
Method: POST
请求参数
Headers
| 参数名称 | 是否必须 | 备注 |
|---|---|---|
| Authorization | 是 | 认证token,格式 Bearer <JSON WEB TOKEN> |
Body
| 参数名称 | 是否必传 | 类型 | 说明 |
|---|---|---|---|
| name | 是 | String | 分类名称 |
返回数据
| 字段名称 | 说明 |
|---|---|
| name | 分类名称 |
| _id | mongoose 默认分配的 id 字段,当访问 id 时就是获取的它 |
| _v | mongoose 默认分配的 versionKey 字段 |
| createdAt | 创建 Schema 时指定分配的自动管理的 createdAt 字段 |
| updatedAt | 创建 Schema 时指定分配的自动管理的 updatedAt 字段 |
创建产品分类 Schema
// models\category.js
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const categorySchema = new mongoose.Schema(
{
// 分类名称
name: {
type: String,
trim: true,
required: [true, '请传入名称'],
maxlength: 32,
unique: true
}
},
{
timestamps: true
}
)
categorySchema.plugin(uniqueValidator, { message: '{VALUE} 已经存在,请更换' })
module.exports = mongoose.model('Category', categorySchema)
分类只有一个 name 字段,不用为它单独创建验证器,使用 mongoose 的即可。
定义 api
// controllers\category.js
const Category = require('../models/category')
const { errorHandler } = require('../helpers/dbErrorHandler')
// 创建分类
const create = (req, res) => {
const category = new Category(req.body)
category.save((error, category) => {
if (error) {
return res.status(400).json(errorHandler(error))
}
res.json(category)
})
}
module.exports = {
create
}
创建管理员身份验证器
创建产品分类仅限管理员身份,创建一个管理员身份验证器
// validator\user.js
...
// 验证是否是管理员
const adminValidator = (req, res, next) => {
if (req.profile.role !== 1) {
return res.status(403).json(errorHandler('只有管理员才有操作权限'))
}
next()
}
module.exports = {
userSignupValidator,
userSigninValidator,
tokenParser,
authValidator,
updateValidator,
adminValidator
}
配置 api
// routes\category.js
const express = require('express')
const { tokenParser, authValidator, adminValidator } = require('../validator/user')
const { create } = require('../controllers/category')
const { getUserById } = require('../controllers/user')
const router = express.Router()
// 创建分类
router.post('/category/create/:userId', [tokenParser, authValidator, adminValidator], create)
// 监听路由参数
// 根据 id 获取用户信息
router.param('userId', getUserById)
module.exports = router
收集路由配置
// routes\index.js
const userRoutes = require('./user')
const categoryRoutes = require('./category')
module.exports = [userRoutes, categoryRoutes]
修改 app.js
// app.js
...
// api
const routes = require('./routes')
...
// 接口配置
app.use('/api', routes)
...
创建管理员用户,可以在数据库手动修改用户的 role 为 1将用户改为管理员,然后再测试 api。
api-分类管理-根据分类 id 获取分类信息
api 设计
基本信息
Path: /category/:categoryId
Method: GET
返回数据
| 字段名称 | 说明 |
|---|---|
| name | 分类名称 |
| _id | mongoose 默认分配的 id 字段,当访问 id 时就是获取的它 |
| _v | mongoose 默认分配的 versionKey 字段 |
| createdAt | 创建 Schema 时指定分配的自动管理的 createdAt 字段 |
| updatedAt | 创建 Schema 时指定分配的自动管理的 updatedAt 字段 |
定义获取分类信息的前置路由中间件和 api
// controllers\category.js
const Category = require('../models/category')
const { errorHandler } = require('../helpers/dbErrorHandler')
// 创建分类
const create = (req, res) => {...}
// 根据 id 获取分类信息
const getCategoryById = (req, res, next, id) => {
Category.findById(id, (error, category) => {
if (error || !category) {
return res.status(400).json(errorHandler('分类不存在'))
}
req.category = category
next()
})
}
// 返回分类信息
const read = (req, res) => {
res.json(req.category)
}
module.exports = {
create,
getCategoryById,
read
}
配置 api
// routes\category.js
const express = require('express')
const { tokenParser, authValidator, adminValidator } = require('../validator/user')
const { create, read, getCategoryById } = require('../controllers/category')
const { getUserById } = require('../controllers/user')
const router = express.Router()
// 创建分类
router.post('/category/create/:userId', [tokenParser, authValidator, adminValidator], create)
// 根据 id 获取分类信息
router.get('/category/:categoryId', read)
// 监听路由参数
// 根据 id 获取用户信息
router.param('userId', getUserById)
// 根据 id 获取分类信息
router.param('categoryId', getCategoryById)
module.exports = router
api-分类管理-根据分类 id 更新分类
api 设计
基本信息
Path: /category/:categoryId/:userId
Method: PUT
请求参数
Headers
| 参数名称 | 是否必须 | 备注 |
|---|---|---|
| Authorization | 是 | 认证token,格式 Bearer <JSON WEB TOKEN> |
Body
| 参数名称 | 是否必传 | 类型 | 说明 |
|---|---|---|---|
| name | 是 | String | 分类名称 |
返回数据
| 字段名称 | 说明 |
|---|---|
| name | 分类名称 |
| _id | mongoose 默认分配的 id 字段,当访问 id 时就是获取的它 |
| _v | mongoose 默认分配的 versionKey 字段 |
| createdAt | 创建 Schema 时指定分配的自动管理的 createdAt 字段 |
| updatedAt | 创建 Schema 时指定分配的自动管理的 updatedAt 字段 |
定义 api
// controllers\category.js
...
// 根据 id 更新分类信息
const update = (req, res) => {
const category = req.category
if (!req.body.name) {
return res.status(400).json(errorHandler('请传入分类名称'))
}
category.name = req.body.name
category.save((error, category) => {
if (error) {
return res.status(400).json(errorHandler(error))
}
res.json(category)
})
}
module.exports = {
create,
getCategoryById,
read,
update
}
配置 api
// routes\category.js
const express = require('express')
const { tokenParser, authValidator, adminValidator } = require('../validator/user')
const { create, read, getCategoryById, update } = require('../controllers/category')
const { getUserById } = require('../controllers/user')
const router = express.Router()
// 创建分类
router.post('/category/create/:userId', [tokenParser, authValidator, adminValidator], create)
// 根据 id 获取分类信息
router.get('/category/:categoryId', read)
// 根据 id 更新分类信息
router.put('/category/:categoryId/:userId', [tokenParser, authValidator, adminValidator], update)
// 监听路由参数
// 根据 id 获取用户信息
router.param('userId', getUserById)
// 根据 id 获取分类信息
router.param('categoryId', getCategoryById)
module.exports = router
api-分类管理-获取分类列表
api 设计
基本信息
Path: /categories
Method: GET
返回数据
返回一个分类信息组成的数组。
定义 api
// controllers\category.js
...
// 获取分类列表
const list = (req, res) => {
Category.find((error, list) => {
if (error) {
return res.status(400).json(errorHandler(error))
}
res.json(list)
})
}
module.exports = {
create,
getCategoryById,
read,
update,
list
}
配置 api
// routes\category.js
const express = require('express')
const { tokenParser, authValidator, adminValidator } = require('../validator/user')
const { create, read, getCategoryById, update, list } = require('../controllers/category')
const { getUserById } = require('../controllers/user')
const router = express.Router()
// 创建分类
router.post('/category/create/:userId', [tokenParser, authValidator, adminValidator], create)
// 根据 id 获取分类信息
router.get('/category/:categoryId', read)
// 根据 id 更新分类信息
router.put('/category/:categoryId/:userId', [tokenParser, authValidator, adminValidator], update)
// 获取分类列表
router.get('/categories', list)
// 监听路由参数
// 根据 id 获取用户信息
router.param('userId', getUserById)
// 根据 id 获取分类信息
router.param('categoryId', getCategoryById)
module.exports = router
本文详细介绍了创建、获取、更新和列出分类的API设计与实现。包括使用Mongoose进行数据验证,管理员权限验证,以及Express路由配置。通过示例展示了如何处理请求参数、返回数据和错误处理。此外,还提供了获取分类列表的API。
849

被折叠的 条评论
为什么被折叠?



