🌳
pt0/serverF/ptDiskF/memoTmpfileF.mts
1import * as _ from 'lodash-es'
2import { calcHash } from '../calcHashF.mts'
5import { pathJoin } from '../pathF.mts'
8import { type absFileDirPath } from '../../ptDirF.mts'
10export const jsonMemoFile = async <T = unknown,>(path : absFileDirPath, calcFn : () => Promise<T> | T, alwaysWrite = false) => {
11 const contents = await read1FileIfExist(path)
12 if (!alwaysWrite && contents) {
13 return {cacheHit: true, jsonH: json1Parse(contents) as T}
14 }
15 const resObj = await calcFn()
16 await write1File(path, JSON.stringify(resObj))
17 return {cacheHit: false, jsonH: resObj}
20export const runMemoTempfile = async <T = unknown,>({cacheKeyA} : {cacheKeyA: string | string[]}, calcFn : () => Promise<T> | T): Promise<T> => {
21 const ptTmpDir = await ensureTmpDirExists()
22 const cachedResPath = pathJoin(ptTmpDir, calcHash(_.castArray(cacheKeyA).join('-')))
23 return (await jsonMemoFile(cachedResPath, calcFn)).jsonH
26export const runMemoTempfileWithHit = async <T = unknown,>({cacheKeyA} : {cacheKeyA: string | string[]}, calcFn : () => Promise<T> | T) => {
27 const ptTmpDir = await ensureTmpDirExists()
28 const cachedResPath = pathJoin(ptTmpDir, calcHash(_.castArray(cacheKeyA).join('-')))
29 const {cacheHit, jsonH} = await jsonMemoFile(cachedResPath, calcFn)
30 return {cacheHit, value: jsonH}
33export const readMemoTempfileIfExist = async <T = unknown,>({cacheKeyA} : {cacheKeyA: string | string[]}): Promise<T | undefined> => {
34 const ptTmpDir = await ensureTmpDirExists()
35 const cachedResPath = pathJoin(ptTmpDir, calcHash(_.castArray(cacheKeyA).join('-')))
36 const contents = await read1FileIfExist(cachedResPath)
37 return contents ? json1Parse(contents) as T : undefined