「16」next-shopping:代码调整+商品、订单api实现

调整

本次调整我们主要是针对数据相关操作和权限相关都聚合在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.jshelpers/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: truepaid:true

代码地址:github.com/liyunfu1998...

相关推荐
y先森4 小时前
CSS3中的伸缩盒模型(弹性盒子、弹性布局)之伸缩容器、伸缩项目、主轴方向、主轴换行方式、复合属性flex-flow
前端·css·css3
前端Hardy4 小时前
纯HTML&CSS实现3D旋转地球
前端·javascript·css·3d·html
susu10830189114 小时前
vue3中父div设置display flex,2个子div重叠
前端·javascript·vue.js
IT女孩儿5 小时前
CSS查缺补漏(补充上一条)
前端·css
吃杠碰小鸡6 小时前
commitlint校验git提交信息
前端
虾球xz7 小时前
游戏引擎学习第20天
前端·学习·游戏引擎
我爱李星璇7 小时前
HTML常用表格与标签
前端·html
疯狂的沙粒7 小时前
如何在Vue项目中应用TypeScript?应该注意那些点?
前端·vue.js·typescript
小镇程序员7 小时前
vue2 src_Todolist全局总线事件版本
前端·javascript·vue.js
野槐7 小时前
前端图像处理(一)
前端