Express + Ts 书写用户的curd例子学习

104 阅读3分钟

技术栈

express typescript mongoose``pnpm

项目初始化

# 初始化

pnpm init

# 初始化git仓库

pnpm add express

# 安装typescript

# ts-node-dev 监听文件变化重启服务,并共享ts的结果,白话就是node运行并监听ts文件

# 安装express、node的声明文件

pnpm add typescript ts-node-dev @types/express @types/node --save-dev

package.json新增启动脚本


"scripts": {
  "dev": "ts-node-dev --respawn --transpile-only src/app.ts"
},

根目录新建.gitignore

node_modules
build

ts环境配置,这在上一章有过介绍 新建tsconfig.json

{
  "compilerOptions": {
    "outDir": "build",
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

入口文件 app.ts的创建

我们书写一个简单的例子 例如 我们想要读取到 这个 db.json里面的数据

{
  "user": [
    {
      "id": 1,
      "username": "xiao",
      "age": 18
    },
    {
      "id": 2,
      "username": "li",
      "age": 18
    }
  ],
  "video": []
}

app.ts

import express from 'express'
import fs from 'fs'
import path from 'path'
const app = express()

interface DbInterface {
  user: Record<string, any>[]
  video: Record<string, any>[]
}

app.get('/', async (req, res) => {
  try {
    const back = await fs.promises.readFile(
      path.resolve(__dirname, 'db.json'),
      'utf-8'
    )
    const result: DbInterface = JSON.parse(back)
    res.send(result.user)
  } catch (error) {
    res.status(500).json({ error })
  }
})

app.listen(3000, () => console.log('Run http://127.0.0.1:3000'))

启动项目 命令

pnpm dev

处理客户端的post

处理数据 'content-type': 'application/x-www-form-urlencoded' 类型

使用中间件 进行解析 才能再 req.body中拿到该类型的数据

处理 json数据格式

总结 : 一般 就是这两种数据 格式需要我们处理 处理的方式 也很简单的就是添加相应的 express 自带的中间件

添加用户数据

这里 主要学习到的 是对 req.body传入数据的 操作

以及学习到 对 状态码以及返回个客户端的信息

// 添加用户数据
app.post('/', async (req, res) => {
  const body = req.body
  // 判断 是否传入数据
  if (!body) res.status(403).json({ error: '缺少用户信息' })

  // 读取数据 得到 最后一个数据的 id 进行累加
  const back = await fs.promises.readFile(
    path.resolve(__dirname, 'db.json'),
    'utf-8'
  )
  const result: DbInterface = JSON.parse(back)
  body.id = result.user[result.user.length - 1].id + 1
  // 将新的数据 进行push
  result.user.push(body)
  // 对数据 进行重新的写入 实现添加数据功能
  try {
    const w = await fs.promises.writeFile(
      path.resolve(__dirname, 'db.json'),
      JSON.stringify(result)
    )
    res.status(200).json({ message: '添加成功' })
  } catch (error) {
    res.status(500).json({ error })
  }
})

修改用户信息

// 修改用户信息
app.put('/:id', async (req: Request, res: Response) => {
  // console.log(req.params.id)
  try {
    // 获取用户列表信息
    const userInfo: DbInterface = JSON.parse(
      await fs.promises.readFile(path.resolve(__dirname, 'db.json'), 'utf-8')
    )
    // 获取当前用户id 
    const userId = Number.parseInt(req.params.id)
    // 查找当前用户是否存在
    const user: User = userInfo.user.find((item) => item.id === userId) as any
    if (!user) {
      res.status(403).json({ message: '用户不存在' })
    } else {
      // 对传入的信息 做判断 是否有 可以不传入了 不传入就不进行修改
      const body: User = req.body
      user.username = body.username ? body.username : user.username
      user.age = body.age ? body.age : user.age

      // 再用户列表找到对应的 用户信息 进行覆盖重写
      userInfo.user[userId - 1] = user

      // 对文件信息进行重写
      await fs.promises.writeFile(
        path.resolve(__dirname, 'db.json'),
        JSON.stringify(userInfo, null, 2)
      )
      res.status(200).json({ message: '修改成功' })
    }
  } catch (error) {
    res.status(500).json({ error })
  }
})

删除用户信息

// 删除用户信息
app.delete('/:id', async (req: Request, res: Response) => {
  try {
    // 第一步还是 读取到使用所有的用户信息
    const userInfo: DbInterface = JSON.parse(
      await fs.promises.readFile(path.resolve(__dirname, 'db.json'), 'utf-8')
    )
    // 获取传入的 id 进行转换为 数值类型
    const userid = Number.parseInt(req.params.id)
    // 进行查找看是否存在该用户
    const user = userInfo.user.find((item) => item.id === userid)
    if (!user) {
      res.status(403).json({ message: '用户不存在 ~' })
    } else {
      // 通过id 对比找出 对应的 数组索引 进行删除 
      const index = userInfo.user.findIndex((ele) => ele.id === userid)
      userInfo.user.splice(index, 1)

      // 写入数据 进行覆盖
      await fs.promises.writeFile(
        path.resolve(__dirname, 'db.json'),
        JSON.stringify(userInfo, null, 2)
      )

      res.status(200).json({ message: '删除成功 ~' })
    }
  } catch (error) {
    res.status(500).json({ error })
  }
})