Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多个mock模块如何公用一套数据? #47

Closed
duxphp opened this issue Aug 25, 2023 · 5 comments
Closed

多个mock模块如何公用一套数据? #47

duxphp opened this issue Aug 25, 2023 · 5 comments

Comments

@duxphp
Copy link

duxphp commented Aug 25, 2023

做示例数据时需要多个*.mock.ts同时公用一套数据,但是用单例类模式也会在每个mock模块中重新生成数据,导致列表和编辑不是一条数据

@pengzhanbo
Copy link
Owner

由于插件是对 每个 *.mock.ts 进行独立编译的,其 import * from './data.ts 对于每个 *.mock.ts 编译后,都隔离在各自作用域中,并不共享。

对于 需要 实现对数据的操作并保存操作后的结果,建议使用 lowdb 之类的 nosql ,将数据保存到本地文件中,通过 lowdb 对文件中的数据进行操作。实现数据持久化。

db.ts

import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'

const __dirname = dirname(fileURLToPath(import.meta.url))

export function createDBHelper(filename: string) {
  const file = join(__dirname, filename)
  const adapter = new JSONFile(file)
  const defaultData = { posts: [] }
  const db = new Low(adapter, defaultData)
  return db
}

*.mock.ts

import { defineConfig } from 'vite-plugin-mock-dev-server'
import { createDBHelper } from './db'

const db = createDBHelper('data.json')

export default defineConfig({
  url: '/api/post',
  body: async () => {
     await db.read()
     return db.data.posts
  }
})
import { defineConfig } from 'vite-plugin-mock-dev-server'
import { createDBHelper } from './db'

const db = createDBHelper('data.json')

export default defineConfig({
  url: '/api/post/delete',
  body: async (query) => {
    await db.read()
    db.data.posts.splice(0, 1)
    await db.write()
    return { message: 'success' }
  }
})

@pengzhanbo
Copy link
Owner

根据这类场景,目前我计划在 插件中 新增一个 defineMockData(key, data) 的函数,对数据进行包装,实现共享。

@duxphp
Copy link
Author

duxphp commented Aug 26, 2023

好的,谢谢,目前先用 nosql 了

@pengzhanbo
Copy link
Owner

pengzhanbo commented Aug 26, 2023

@duxphp

已在 v1.3.1 版本中添加了 defineMockData(key, data) 的支持。具体使用方式请查看 文档

由于是基于 memory ,每次重启开发服务,数据都会重置。如果有 数据持久化的需求,建议还是 nosql ,将数据保存到本地文件中维护。

@duxphp
Copy link
Author

duxphp commented Aug 27, 2023

谢谢 更新太快了

@duxphp duxphp closed this as completed Aug 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants