npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

yc-virtual-backend

v0.0.6

Published

前端虚拟后台插件 - 基于 yc-web-db 实现

Readme

YC Virtual Backend - 前端虚拟后台插件

基于 yc-web-db 实现的前端虚拟后台插件,提供完整的 RESTful API 模拟功能,支持请求拦截、路由管理、数据库操作、事务处理等功能。

特性

  • 🚀 请求拦截 - 拦截浏览器 HTTP 请求(fetch/XMLHttpRequest)
  • 🛣️ 路由管理 - 支持 RESTful 风格的路由定义
  • 🗄️ 数据库集成 - 基于 yc-web-db 的本地数据库支持
  • 🔄 事务支持 - 数据库事务操作,保证数据一致性
  • Web Worker - 支持大数据量 SQL 执行
  • 🎛️ 灵活配置 - 支持全局/控制器/路由级别的延迟配置
  • 📝 TypeScript - 完整的类型定义支持

安装

npm install yc-virtual-backend

快速开始

基础用法

import { VirtualBackend } from 'yc-virtual-backend'

// 创建虚拟后台实例
const virtualBackend = new VirtualBackend({
  delay: 300, // 模拟网络延迟 300ms
  db: {
    my_database: {
      user_table: [
        { name: 'id', type: 'INT', key: 'PRI', autoIncrement: true, nullable: false },
        { name: 'name', type: 'VARCHAR', length: 255, nullable: false },
        { name: 'email', type: 'VARCHAR', length: 255 }
      ]
    }
  }
})

// 注册用户控制器
const userController = virtualBackend.registerController('User', {
  basePath: '/api/user'
})

// 注册路由
userController
  .get('/list', async (data, headers) => {
    const db = virtualBackend.getDB('my_database')
    const users = await db.select('SELECT * FROM user_table')
    return { code: 200, msg: '获取成功', data: users }
  })
  .post('/create', async (data, headers) => {
    const db = virtualBackend.getDB('my_database')
    const { name, email } = data
    await db.insertSQL(`INSERT INTO user_table (name, email) VALUES ("${name}", "${email}")`)
    return { code: 200, msg: '创建成功' }
  })

// 现在可以像调用真实 API 一样使用
fetch('/api/user/list')
  .then(res => res.json())
  .then(data => console.log(data))

API 文档

VirtualBackend

虚拟后台主类,负责初始化拦截器、管理控制器、处理请求分发。

构造函数

constructor(options?: VirtualBackendOptions)

VirtualBackendOptions 配置项:

| 属性 | 类型 | 默认值 | 说明 | |------|------|--------|------| | autoInit | boolean | true | 是否自动初始化 | | enabled | boolean | true | 是否启用请求拦截 | | interceptMode | 'all' | 'registered' | 'registered' | 拦截模式 | | delay | number | 0 | 全局延迟时间(ms) | | db | DBConfig | {} | 数据库配置 |

示例:

const virtualBackend = new VirtualBackend({
  autoInit: true,
  enabled: true,
  interceptMode: 'registered', // 只拦截已注册的路由
  delay: 300, // 全局延迟 300ms
  db: {
    my_database: {
      user_table: [
        { name: 'id', type: 'INT', key: 'PRI', autoIncrement: true },
        { name: 'name', type: 'VARCHAR', length: 255 }
      ]
    }
  }
})

方法

registerController

注册控制器

registerController(name: string, config?: ControllerConfig): Controller

参数:

  • name - 控制器名称
  • config - 控制器配置(可选)
    • basePath - 基础路径,默认 /api/{name.toLowerCase()}

返回: Controller 实例

示例:

const userController = virtualBackend.registerController('User', {
  basePath: '/api/user'
})
getDB

获取数据库管理器

getDB(dbName: string): UserDatabaseManager

参数:

  • dbName - 数据库名称

返回: UserDatabaseManager 实例

示例:

const db = virtualBackend.getDB('my_database')
const users = await db.select('SELECT * FROM user_table')
executeTransaction

执行数据库事务

executeTransaction<T>(
  dbName: string,
  mode: 'rw' | 'r',
  tables: string[],
  callback: (db: UserDatabaseManager) => Promise<T>
): Promise<T>

参数:

  • dbName - 数据库名称
  • mode - 事务模式:'rw'(读写)或 'r'(只读)
  • tables - 涉及的表名数组
  • callback - 事务回调函数

示例:

// 转账事务示例
await virtualBackend.executeTransaction(
  'my_database',
  'rw',
  ['accounts'],
  async (db) => {
    // 扣减张三余额
    await db.updateSQL('UPDATE accounts SET balance = balance - 100 WHERE username = "张三"')
    // 增加李四余额
    await db.updateSQL('UPDATE accounts SET balance = balance + 100 WHERE username = "李四"')
  }
)
batchTransaction

执行批量事务

batchTransaction<T>(
  dbName: string,
  operations: ((db: UserDatabaseManager) => Promise<T>)[]
): Promise<T[]>

参数:

  • dbName - 数据库名称
  • operations - 操作函数数组

示例:

const results = await virtualBackend.batchTransaction('my_database', [
  async (db) => {
    // 创建订单
    return await db.insertSQL('INSERT INTO orders ...')
  },
  async (db) => {
    // 扣减库存
    return await db.updateSQL('UPDATE inventory ...')
  },
  async (db) => {
    // 记录日志
    return await db.insertSQL('INSERT INTO logs ...')
  }
])
setEnabled

启用/禁用请求拦截

setEnabled(enabled: boolean): void

示例:

virtualBackend.setEnabled(false) // 禁用拦截
virtualBackend.setEnabled(true)  // 启用拦截
setDelay

设置全局延迟

setDelay(delay: number): void

示例:

virtualBackend.setDelay(500) // 设置 500ms 延迟
setInterceptMode

设置拦截模式

setInterceptMode(mode: 'all' | 'registered'): void

模式说明:

  • 'all' - 拦截所有请求,未匹配路由返回 404
  • 'registered' - 只拦截已注册的路由,未匹配路由放行
getControllers

获取所有控制器

getControllers(): Controller[]
getDBNames

获取所有数据库名称

getDBNames(): string[]
destroy

销毁虚拟后台实例

destroy(): void

示例:

onUnmounted(() => {
  virtualBackend.destroy()
})

Controller

控制器类,用于组织和管理相关的 API 接口。

属性

name

控制器名称(只读)

readonly name: string
basePath

基础路径(只读)

readonly basePath: string

方法

register

注册通用路由

register<T, R>(
  method: RequestMethod,
  path: string,
  handler: HandlerType<T, R>,
  responseHandler?: ResponseHandlerType<R>,
  delay?: number
): this

参数:

  • method - HTTP 方法:'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  • path - 路径(相对于 basePath)
  • handler - 处理函数
  • responseHandler - 响应处理函数(可选)
  • delay - 路由级别延迟(可选)

示例:

userController.register(
  'GET',
  '/:id',
  async (data, headers) => {
    const { id } = data._params
    const db = virtualBackend.getDB('my_database')
    const user = await db.select(`SELECT * FROM user_table WHERE id = ${id}`)
    return { code: 200, msg: '获取成功', data: user[0] }
  }
)
get / post / put / delete / patch

快捷方法,对应 HTTP 方法

get<T, R>(
  path: string,
  handler: HandlerType<T, R>,
  responseHandler?: ResponseHandlerType<R>,
  delay?: number
): this

post<T, R>(...): this
delete<T, R>(...): this
put<T, R>(...): this
patch<T, R>(...): this

示例:

userController
  .get('/list', handler)
  .post('/create', handler)
  .put('/:id', handler)
  .delete('/:id', handler)
getRoutes

获取所有路由配置

getRoutes(): ApiDefinition[]
setEnabled

设置路由启用/禁用状态

setEnabled(url: string | string[], enabled: boolean): void

示例:

// 禁用单个路由
userController.setEnabled('/list', false)

// 禁用多个路由
userController.setEnabled(['/list', '/create'], false)
deregister

注销路由

deregister(url: string | string[]): void

示例:

// 注销单个路由
userController.deregister('/list')

// 注销多个路由
userController.deregister(['/list', '/create'])
setDelay

设置控制器级别的延迟

setDelay(delay: number): void

示例:

userController.setDelay(500) // 该控制器下所有路由延迟 500ms
setRouteDelay

设置单个路由的延迟

setRouteDelay(path: string, delay: number): void

示例:

userController.setRouteDelay('/list', 1000) // 该路由延迟 1 秒
clear

清空所有路由

clear(): void

HandlerType

路由处理函数类型

type HandlerType<T = any, R = any> = (
  data: T,
  headers: RequestHeaders
) => Promise<ApiResponse<R>> | ApiResponse<R>

参数:

  • data - 请求数据(包含 body 和 URL 参数)
    • data._params - URL 参数(如 :id
    • data._body - 请求体
  • headers - 请求头

返回: ApiResponse 对象

interface ApiResponse<T = any> {
  code: number      // 状态码
  msg: string       // 消息
  data?: T          // 数据(可选)
  timestamp?: number // 时间戳(可选)
}

示例:

const handler: HandlerType = async (data, headers) => {
  const { id } = data._params  // 获取 URL 参数
  const { name } = data        // 获取请求体数据
  
  return {
    code: 200,
    msg: '成功',
    data: { id, name }
  }
}

useVirtualSqlWorker

Web Worker SQL 执行组合式函数(Vue 3)

import { useVirtualSqlWorker } from 'yc-virtual-backend'

const {
  isExecuting,    // 是否执行中(computed)
  progress,       // 执行进度(computed)
  result,         // 执行结果(computed)
  error,          // 错误信息(computed)
  state,          // 完整状态(ref)
  executeSql,     // 执行单条 SQL
  executeBatch,   // 批量执行 SQL
  executeScript   // 执行 SQL 脚本
} = useVirtualSqlWorker()

注意: Web Worker 功能需要 yc-web-db 正确初始化。如果 Web Worker 不可用,建议使用普通的数据库操作方法。


数据库操作

yc-virtual-backend 集成了 yc-web-db,支持完整的数据库操作。

SQL 执行方法

const db = virtualBackend.getDB('my_database')

// SELECT 查询
const users = await db.select('SELECT * FROM user_table WHERE age > 18')

// INSERT 插入
const insertCount = await db.insertSQL('INSERT INTO user_table (name, email) VALUES ("张三", "[email protected]")')

// UPDATE 更新
const updateCount = await db.updateSQL('UPDATE user_table SET age = 20 WHERE id = 1')

// DELETE 删除
const deleteCount = await db.deleteSQL('DELETE FROM user_table WHERE id = 1')

// 通用执行
const result = await db.execute('SELECT * FROM user_table')

表操作

// 创建表
await db.createTable('products', [
  { name: 'id', type: 'INT', key: 'PRI', autoIncrement: true },
  { name: 'name', type: 'VARCHAR', length: 100 },
  { name: 'price', type: 'DECIMAL', length: 10, decimal: 2 }
])

// 删除表
await db.dropTable('products')

// 获取表列表
const tables = await db.getTables()

// 获取表结构
const schema = await db.getTableSchema('products')

延迟配置

支持三个级别的延迟配置,优先级:路由级别 > 控制器级别 > 全局级别

全局延迟

const virtualBackend = new VirtualBackend({ delay: 300 })
// 或
virtualBackend.setDelay(500)

控制器级别延迟

const controller = virtualBackend.registerController('User')
controller.setDelay(500) // 该控制器下所有路由延迟 500ms

路由级别延迟

// 注册时设置
controller.get('/list', handler, undefined, 1000)

// 或后续设置
controller.setRouteDelay('/list', 1000)

完整示例

import { VirtualBackend } from 'yc-virtual-backend'
import { onMounted, onUnmounted } from 'vue'

let virtualBackend: VirtualBackend | null = null

onMounted(async () => {
  // 创建实例
  virtualBackend = new VirtualBackend({
    delay: 300,
    db: {
      shop: {
        products: [
          { name: 'id', type: 'INT', key: 'PRI', autoIncrement: true },
          { name: 'name', type: 'VARCHAR', length: 100 },
          { name: 'price', type: 'DECIMAL', length: 10, decimal: 2 },
          { name: 'stock', type: 'INT' }
        ],
        orders: [
          { name: 'id', type: 'INT', key: 'PRI', autoIncrement: true },
          { name: 'product_id', type: 'INT' },
          { name: 'quantity', type: 'INT' },
          { name: 'total', type: 'DECIMAL', length: 10, decimal: 2 }
        ]
      }
    }
  })

  // 注册产品控制器
  const productController = virtualBackend.registerController('Product', {
    basePath: '/api/products'
  })

  productController
    .get('/list', async () => {
      const db = virtualBackend!.getDB('shop')
      const products = await db.select('SELECT * FROM products')
      return { code: 200, msg: '获取成功', data: products }
    })
    .post('/create', async (data) => {
      const db = virtualBackend!.getDB('shop')
      const { name, price, stock } = data
      await db.insertSQL(`INSERT INTO products (name, price, stock) VALUES ("${name}", ${price}, ${stock})`)
      return { code: 200, msg: '创建成功' }
    })

  // 注册订单控制器
  const orderController = virtualBackend.registerController('Order', {
    basePath: '/api/orders'
  })

  orderController
    .post('/create', async (data) => {
      const db = virtualBackend!.getDB('shop')
      const { product_id, quantity } = data
      
      // 使用事务确保数据一致性
      await virtualBackend!.executeTransaction('shop', 'rw', ['products', 'orders'], async () => {
        // 查询产品
        const product = await db.select(`SELECT * FROM products WHERE id = ${product_id}`)
        if (product.length === 0) throw new Error('产品不存在')
        if (product[0].stock < quantity) throw new Error('库存不足')
        
        // 扣减库存
        await db.updateSQL(`UPDATE products SET stock = stock - ${quantity} WHERE id = ${product_id}`)
        
        // 创建订单
        const total = product[0].price * quantity
        await db.insertSQL(`INSERT INTO orders (product_id, quantity, total) VALUES (${product_id}, ${quantity}, ${total})`)
      })
      
      return { code: 200, msg: '订单创建成功' }
    })
})

onUnmounted(() => {
  virtualBackend?.destroy()
})

注意事项

  1. 数据库初始化 - 首次使用时会自动创建数据库和表
  2. 延迟优先级 - 路由级别 > 控制器级别 > 全局级别
  3. 事务回滚 - 事务中任何操作失败会自动回滚所有修改
  4. Web Worker - 大数据量操作建议使用 Web Worker 避免阻塞主线程
  5. 内存管理 - 组件卸载时建议调用 destroy() 清理资源

开发团队

洋铲工作室 - 让你体验不一样的低代码

  • 官网: http://www.yangchan.work
  • 天幕低代码: http://www.yangchan.work/skyCurtain/