Files
Compass/backend/shared/src/firebase-utils.ts
Martin Braquet ba9b3cfb06 Add pretty formatting (#29)
* Test

* Add pretty formatting

* Fix Tests

* Fix Tests

* Fix Tests

* Fix

* Add pretty formatting fix

* Fix

* Test

* Fix tests

* Clean typeckech

* Add prettier check

* Fix api tsconfig

* Fix api tsconfig

* Fix tsconfig

* Fix

* Fix

* Prettier
2026-02-20 17:32:27 +01:00

49 lines
1.5 KiB
TypeScript

import {ENV_CONFIG, getStorageBucketId} from 'common/envs/constants'
import {getStorage, Storage} from 'firebase-admin/storage'
import {readFileSync} from 'fs'
export const getServiceAccountCredentials = () => {
let keyPath = ENV_CONFIG.googleApplicationCredentials
// console.debug('Using GOOGLE_APPLICATION_CREDENTIALS:', keyPath)
if (!keyPath) {
// throw new Error(
// `Please set the GOOGLE_APPLICATION_CREDENTIALS environment variable to contain the path to your key file.`
// )
return {}
}
if (!keyPath.startsWith('/')) {
// Make relative paths relative to the current file
keyPath = __dirname + '/' + keyPath
// console.debug(keyPath)
}
try {
return JSON.parse(readFileSync(keyPath, {encoding: 'utf8'}))
} catch (e) {
throw new Error(`Failed to load service account key from ${keyPath}: ${e}`)
}
}
export function getBucket() {
return getStorage().bucket(getStorageBucketId())
}
export type Bucket = ReturnType<InstanceType<typeof Storage>['bucket']>
export async function deleteUserFiles(username: string) {
const path = `user-images/${username}`
// Delete all files in the directory
const bucket = getBucket()
const [files] = await bucket.getFiles({prefix: path})
if (files.length === 0) {
console.debug(`No files found in bucket for user ${username}`)
return
}
await Promise.all(files.map((file) => file.delete()))
console.debug(`Deleted ${files.length} files for user ${username}`)
}