Files
supabase/apps/docs/features/helpers.fs.ts
Charis 7c20407302 refactor(docs): type spec parsing + testing setup (#27931)
This produces more complete type information (unions, following type alias refererences that aren't successfully dereferenced at an earlier stage, etc.), in a format that is much easier to query from UI components. Also adds a snapshot test for easier future iteration.

I had a lot of trouble configuring Jest for the snapshot tests (something to do with imports and compile targets), and there are zero other tests in this directory right now, so I just tore out the test setup and replaced it with Vitest. Much faster!
2024-07-17 10:48:26 -04:00

54 lines
1.3 KiB
TypeScript

import { watch } from 'node:fs'
import { stat } from 'node:fs/promises'
import { IS_DEV } from '~/lib/constants'
import type { OrPromise } from '~/features/helpers.types'
/**
* Caches a function for the length of the server process.
*
* In DEV, watches a directory to cache bust on edit.
*/
export const cache_fullProcess_withDevCacheBust = <Args extends unknown[], Output>(
/**
* The function whose results to cache
*/
fn: (...args: Args) => OrPromise<Output>,
/**
* The directory to watch for edits
*/
watchDirectory: string,
/**
* A function that generates the cache key to bust, given the changed
* filename (relative to the watch directory)
*/
genCacheKeyFromFilename: (filename: string) => string
) => {
const _cache = new Map<string, Output>()
if (IS_DEV) {
watch(watchDirectory, { recursive: true }, (_, filename) => {
if (!filename) return
const cacheKey = genCacheKeyFromFilename(filename)
_cache.delete(cacheKey)
})
}
return async (...args: Args) => {
const cacheKey = JSON.stringify(args)
if (!_cache.has(cacheKey)) {
_cache.set(cacheKey, await fn(...args))
}
return _cache.get(cacheKey)!
}
}
export const existsFile = async (fullPath: string) => {
try {
await stat(fullPath)
return true
} catch {
return false
}
}