refactor: lazily initialize path

This commit is contained in:
Mary
2024-05-08 11:23:31 +07:00
parent c67043738d
commit 36729153cc
+21 -10
View File
@@ -49,9 +49,15 @@ export type ComposerImage =
| ComposerImageWithoutTransformation | ComposerImageWithoutTransformation
| ComposerImageWithTransformation | ComposerImageWithTransformation
const imageCacheDirectory = isNative let _imageCacheDirectory: string
? joinPath(cacheDirectory!, 'bsky-composer')
: null function getImageCacheDirectory(): string | null {
if (isNative) {
return (_imageCacheDirectory ??= joinPath(cacheDirectory!, 'bsky-composer'))
}
return null
}
export async function createComposerImage( export async function createComposerImage(
raw: ImageMeta, raw: ImageMeta,
@@ -200,6 +206,7 @@ export async function compressImage(img: ComposerImage): Promise<ImageMeta> {
const source = img.transformed || img.source const source = img.transformed || img.source
const [w, h] = containImageRes(source.width, source.height, POST_IMG_MAX) const [w, h] = containImageRes(source.width, source.height, POST_IMG_MAX)
const cacheDir = isNative && getImageCacheDirectory()
for (let i = 10; i > 0; i--) { for (let i = 10; i > 0; i--) {
// Float precision // Float precision
@@ -226,7 +233,7 @@ export async function compressImage(img: ComposerImage): Promise<ImageMeta> {
} }
} }
if (imageCacheDirectory) { if (cacheDir) {
await deleteAsync(res.uri) await deleteAsync(res.uri)
} }
} }
@@ -235,10 +242,12 @@ export async function compressImage(img: ComposerImage): Promise<ImageMeta> {
} }
async function moveIfNecessary(from: string) { async function moveIfNecessary(from: string) {
if (cacheDirectory && from.startsWith(cacheDirectory!)) { const cacheDir = isNative && getImageCacheDirectory()
const to = joinPath(imageCacheDirectory!, uuid.v4() + '')
await makeDirectoryAsync(imageCacheDirectory!, {intermediates: true}) if (cacheDir && from.startsWith(cacheDir)) {
const to = joinPath(cacheDir, uuid.v4() + '')
await makeDirectoryAsync(cacheDir, {intermediates: true})
await moveAsync({from, to}) await moveAsync({from, to})
return to return to
@@ -249,9 +258,11 @@ async function moveIfNecessary(from: string) {
/** Purge files that were created to accomodate image manipulation */ /** Purge files that were created to accomodate image manipulation */
export async function purgeTemporaryImageFiles() { export async function purgeTemporaryImageFiles() {
if (imageCacheDirectory) { const cacheDir = isNative && getImageCacheDirectory()
await deleteAsync(imageCacheDirectory, {idempotent: true})
await makeDirectoryAsync(imageCacheDirectory) if (cacheDir) {
await deleteAsync(cacheDir, {idempotent: true})
await makeDirectoryAsync(cacheDir)
} }
} }