调整
本次调整我们主要是针对数据相关操作和权限相关都聚合在helpers
目录下面
修改helpers/auth.js
,更改导出方式,并且可以将utils
下面的token相关的文件删掉了
js
import jwt from 'jsonwebtoken'
function verifyToken(req, isJwt) {
try {
const token = req.headers.get('authorization')
const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET)
const id = decoded.id
return id
} catch (error) {
if (isJwt) {
throw error
}
}
}
function createAccessToken(payload) {
return jwt.sign(payload, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '1d',
})
}
export const auth = {
verifyToken,
createAccessToken,
}
修改helpers/db.js
,删除lib/db.js
js
import mongoose from 'mongoose'
const connection = {}
async function connect() {
if (connection.isConnected) {
console.log('Using existing connection.')
return
}
if (mongoose.connections.length > 0) {
connection.isConnected = mongoose.connections[0].readyState
if (connection.isConnected === 1) {
console.log('Use previous connection')
return
}
await mongoose.disconnect()
}
try {
const db = await mongoose.connect(process.env.MONGODB_URL)
console.log('New connection')
connection.isConnected = db.connections[0].readyState
} catch (error) {
console.log(error)
process.exit(1)
}
}
async function disconnect() {
if (connection.isConnected) {
if (process.env.NODE_ENV === 'production') {
await mongoose.disconnect()
connection.isConnected = false
} else {
console.log('not disconnected')
}
}
}
export const db = { connect, disconnect }
helpers/api/user-repo.js
和helpers/api/category-repo.js
只需要更新db
的引用路径即可:
商品api
repo
新建helpers/repo/product-repo.js
js
import { db } from '@/helpers'
import Product from '@/models/Product'
const getAll = async () => {
await db.connect()
const result = await Product.find()
await db.disconnect()
return result
}
const getById = async id => {
await db.connect()
const result = await Product.findById(id)
if (!result) throw '产品不存在'
await db.disconnect()
return result
}
const create = async params => {
await db.connect()
const newProducts = new Product(params)
await newProducts.save()
await db.disconnect()
}
const _delete = async id => {
await db.connect()
const product = await Product.findById(id)
if (!product) throw '产品不存在'
await Product.findByIdAndDelete(id)
await db.disconnect()
}
const update = async (id, params) => {
await db.connect()
const product = await Product.findById(id)
if (!product) throw '产品不存在'
Object.assign(product, params)
await Product.findByIdAndUpdate(
{
_id: id,
},
{ ...params }
)
await db.disconnect()
}
export const productRepo = {
getAll,
getById,
create,
update,
delete: _delete,
}
然后在helpers/repo/index.js
中导出
api
修改app/api/product/route.js
js
import z from 'zod'
import { setJson, apiHandler } from '@/helpers/api'
import { productRepo } from '@/helpers/repo/product-repo'
const getProduct = apiHandler(async req => {
const result = await productRepo.getAll()
return setJson({
data: result,
})
})
const createProduct = apiHandler(
async req => {
const body = await req.json()
console.log('body', body)
await productRepo.create(body)
return setJson({
message: '新增产品成功',
})
},
{
isJwt: true,
identity: 'admin',
schema: z.object({
title: z.string(),
price: z.number(),
inStock: z.number(),
description: z.string(),
content: z.string(),
category: z.string(),
images: z.array(z.string()),
}),
}
)
export const GET = getProduct
export const POST = createProduct
创建product
效果如下:
获取全部product
效果如下:
修改app/api/product/[id]/route.js
js
import z from 'zod'
import { setJson, apiHandler } from '@/helpers/api'
import { productRepo } from '@/helpers'
const getProduct = apiHandler(async (req, { params }) => {
const { id } = params
const result = await productRepo.getById(id)
return setJson({
data: result,
})
})
const updateProduct = apiHandler(
async (req, { params }) => {
const { id } = params
const body = await req.json()
await productRepo.update(id, body)
return setJson({
message: '更新产品成功',
})
},
{
isJwt: true,
identity: 'admin',
schema: z.object({
title: z.string(),
price: z.number(),
inStock: z.number(),
description: z.string(),
content: z.string(),
category: z.string(),
images: z.array(z.string()),
}),
}
)
const deleteProduct = apiHandler(
async (req, { params }) => {
const { id } = params
await productRepo.delete(id)
return setJson({
message: '删除产品成功',
})
},
{
isJwt: true,
identity: 'admin',
}
)
export const GET = getProduct
export const PUT = updateProduct
export const DELETE = deleteProduct
获取单个product效果如下:
订单api
repo
新建helpers/repo/order-repo.js
js
import { db } from '@/helpers'
import Order from '@/models/Order'
const getAll = async (userId, role) => {
await db.connect()
let orders
console.log('role', role)
if (role !== 'admin') {
orders = await Order.find({
user: userId,
}).populate('user', '-password')
} else {
orders = await Order.find().populate('user', '-password')
}
await db.disconnect()
return orders
}
const getById = async id => {
await db.connect()
const result = await Order.findById(id)
if (!result) throw '订单不存在'
await db.disconnect()
return result
}
const create = async (id, params) => {
await db.connect()
const newOrder = new Order({
user: id,
...params,
})
await newOrder.save()
await db.disconnect()
}
const _delete = async id => {
await db.connect()
const order = await Order.findById(id)
if (!order) throw '订单不存在'
await Order.findByIdAndDelete(id)
await db.disconnect()
}
const update = async (id, params) => {
await db.connect()
const order = await Order.findById(id)
if (!order) throw '订单不存在'
await Order.findByIdAndUpdate({ _id: id }, { ...params })
await db.disconnect()
}
export const orderRepo = {
getAll,
getById,
create,
update,
delete: _delete,
}
api
修改app/api/order/route.js
js
import z from 'zod'
import { setJson, apiHandler } from '@/helpers/api'
import { orderRepo } from '@/helpers'
const getOrders = apiHandler(
async req => {
const userId = req.headers.get('userId')
const role = req.headers.get('userRole')
const result = await orderRepo.getAll(userId, role)
return setJson({
data: result,
})
},
{
isJwt: true,
}
)
const createOrder = apiHandler(
async req => {
const userId = req.headers.get('userId')
const body = await req.json()
await orderRepo.create(userId, body)
return setJson({
message: '创建订单成功',
})
},
{
isJwt: true,
schema: z.object({
address: z.string(),
mobile: z.string(),
cart: z.array(z.string()),
total: z.number(),
}),
}
)
export const GET = getOrders
export const POST = createOrder
效果如下:
修改app/api/order/delivered/[id]/route.js
js
import { setJson, apiHandler } from '@/helpers/api'
import { orderRepo } from '@/helpers'
const deliveredOrder = apiHandler(
async (req, { params }) => {
const { id } = params
const body = {
paid: true,
dateOfPayment: new Date().toISOString(),
method: '在线付款',
delivered: true,
}
await orderRepo.update(id, body)
return setJson({
message: '已经通过确认',
})
},
{
isJwt: true,
identity: 'admin',
}
)
export const PATCH = deliveredOrder
效果如下:
可以看到一个订单已经是delivered: true
和paid:true
了