45 lines
1.4 KiB
JavaScript

import fs from 'node:fs/promises'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
export function createPrintJournal(baseDir) {
const filePath = path.join(baseDir, 'pending-print-result.json')
return {
async load() {
try {
const entry = JSON.parse(await fs.readFile(filePath, 'utf8'))
if (!entry || !Number.isInteger(entry.jobId) || !entry.claimToken ||
!['claimed', 'dispatching', 'completed_pending_ack', 'unknown_pending_ack', 'failed_pending_ack'].includes(entry.phase)) {
throw new Error('本地打印恢复记录损坏,请先核实上一任务的出纸情况')
}
return entry
} catch (error) {
if (error?.code === 'ENOENT') return null
throw error
}
},
async save(entry) {
await fs.mkdir(baseDir, { recursive: true })
const temporaryPath = `${filePath}.${randomUUID()}.tmp`
const file = await fs.open(temporaryPath, 'wx')
try {
await file.writeFile(JSON.stringify(entry))
await file.sync()
} finally {
await file.close()
}
try {
await fs.rename(temporaryPath, filePath)
} catch (error) {
await fs.unlink(temporaryPath).catch(() => {})
throw error
}
},
async clear() {
await fs.unlink(filePath).catch((error) => {
if (error?.code !== 'ENOENT') throw error
})
}
}
}