「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...

相关推荐
2401_8827275711 分钟前
低代码配置式组态软件-BY组态
前端·后端·物联网·低代码·前端框架
NoneCoder14 分钟前
CSS系列(36)-- Containment详解
前端·css
anyup_前端梦工厂25 分钟前
初始 ShellJS:一个 Node.js 命令行工具集合
前端·javascript·node.js
5hand29 分钟前
Element-ui的使用教程 基于HBuilder X
前端·javascript·vue.js·elementui
GDAL1 小时前
vue3入门教程:ref能否完全替代reactive?
前端·javascript·vue.js
六卿1 小时前
react防止页面崩溃
前端·react.js·前端框架
z千鑫1 小时前
【前端】详解前端三大主流框架:React、Vue与Angular的比较与选择
前端·vue.js·react.js
m0_748256142 小时前
前端 MYTED单篇TED词汇学习功能优化
前端·学习
田猿笔记3 小时前
在 Node.js 中正确处理 `async/await` 及数组迭代
node.js
小白学前端6663 小时前
React Router 深入指南:从入门到进阶
前端·react.js·react