Files
shrimp-server/test/exportSheets.test.ts
T
wc24 6dff7b82cc 0.9.0: 导入导出协议改成 sheet 表(多 sheet)
export 返回 { sheet 名: 行数组 },import 收同样的形状 —— 一份负载对应一个 xlsx
工作簿。默认仍是单张表(以 moduleKey 命名),模块重写 export/import 就能自定义
多 sheet(如商品/商店/销售规则一次搬完),不必再把多张表压扁成 __t/__data 两列
塞进一个 sheet。

import 取同名 sheet、没有就退回第一张:手工在 Excel 里建的表叫 Sheet1,老版本
前端发的是裸数组,两种都不该白导。
2026-08-21 20:05:37 +08:00

68 lines
2.8 KiB
TypeScript

import { describe, it, expect } from "vitest"
import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, ShrimpFieldTypes } from "../src/main"
import type { IShrimpSheets } from "../src/main"
type Row = { _id: string; name: string }
function makeModule() {
const shrimp = new Shrimp()
const crud = new MemoryShrimpCrud<Row>()
const mod = new ShrimpTableModule<Row>(shrimp, "tag", crud, [
{ key: "name", label: "名称", type: ShrimpFieldTypes.String },
], "标签")
mod.initCrud()
return { crud, mod }
}
describe("导入导出的 sheet 契约", () => {
it("export 返回以 moduleKey 命名的单张 sheet", async () => {
const { crud, mod } = makeModule()
await crud.add({ name: "热门" } as any)
const sheets = await mod.export({})
expect(Object.keys(sheets)).toEqual(["tag"])
expect(sheets.tag.map(r => r.name)).toEqual(["热门"])
})
it("import 认同名 sheet", async () => {
const { crud, mod } = makeModule()
await mod.import({ other: [{ name: "别人的" }], tag: [{ name: "热门" }] })
const all = await crud.list({})
expect(all.list.map(r => r.name)).toEqual(["热门"])
})
it("没有同名 sheet 时退回第一张(手工 Excel 的 Sheet1)", async () => {
const { crud, mod } = makeModule()
await mod.import({ Sheet1: [{ name: "热门" }] })
expect((await crud.list({})).list.map(r => r.name)).toEqual(["热门"])
})
it("老版本前端发的裸数组仍然能导", async () => {
const { crud, mod } = makeModule()
await mod.import([{ name: "热门" }] as any)
expect((await crud.list({})).list.map(r => r.name)).toEqual(["热门"])
})
it("多 sheet 由模块重写 export/import 自行分派", async () => {
const shrimp = new Shrimp()
const goods = new MemoryShrimpCrud<Row>()
const shops = new MemoryShrimpCrud<Row>()
class ShopModule extends ShrimpTableModule<Row> {
async export(): Promise<IShrimpSheets> {
return { goods: (await goods.list({})).list, shop: (await shops.list({})).list }
}
async import(data?: IShrimpSheets): Promise<void> {
for (const row of data?.goods ?? []) await goods.add(row as any)
for (const row of data?.shop ?? []) await shops.add(row as any)
}
}
const mod = new ShopModule(shrimp, "shop", shops, [
{ key: "name", label: "名称", type: ShrimpFieldTypes.String },
], "商店")
await mod.import({ goods: [{ name: "木剑" }], shop: [{ name: "杂货铺" }] })
const sheets = await mod.export()
expect(sheets.goods.map(r => r.name)).toEqual(["木剑"])
expect(sheets.shop.map(r => r.name)).toEqual(["杂货铺"])
})
})