@supabase-cache-helpers/storage-swr
Version:
A collection of SWR utilities for working with Supabase.
1 lines • 16.7 kB
Source Map (JSON)
{"version":3,"sources":["../src/index.ts","../src/lib/constants.ts","../src/lib/decode.ts","../src/lib/get-bucket-id.ts","../src/lib/key.ts","../src/lib/encode.ts","../src/lib/middleware.ts","../src/lib/truthy.ts","../src/mutate/use-remove-directory.ts","../src/mutate/use-random-key.ts","../src/mutate/use-remove-files.ts","../src/mutate/use-upload.ts","../src/query/use-directory-urls.ts","../src/query/use-directory.ts","../src/query/use-file-url.ts"],"sourcesContent":["export * from './lib';\nexport * from './mutate';\nexport * from './query';\n","export const KEY_PREFIX = 'storage';\nexport const KEY_SEPARATOR = '$';\n","import type { DecodedStorageKey } from '@supabase-cache-helpers/storage-core';\nimport type { Key } from 'swr';\n\nimport { KEY_PREFIX, KEY_SEPARATOR } from './constants';\n\nexport const decode = (key: Key): DecodedStorageKey | null => {\n if (typeof key !== 'string' || !key.startsWith(KEY_PREFIX)) return null;\n const [_, bucketId, path] = key.split(KEY_SEPARATOR);\n return { bucketId, path };\n};\n","import type { StorageFileApi } from './types';\n\nexport const getBucketId = (fileApi: StorageFileApi) =>\n fileApi['bucketId'] as string;\n","import type { Key } from 'swr';\n\nimport type { StorageFileApi } from './types';\n\nexport const isStorageKeyInput = (key: Key): key is StorageKeyInput =>\n Array.isArray(key) &&\n key.length === 2 &&\n typeof key[1] === 'string' &&\n Boolean(key[0]['bucketId']);\n\nexport const assertStorageKeyInput = (key: Key): StorageKeyInput => {\n if (!isStorageKeyInput(key)) throw new Error('Invalid key');\n return key;\n};\n\nexport type StorageKeyInput = [StorageFileApi, string];\n","import type { Key } from 'swr';\n\nimport { KEY_PREFIX, KEY_SEPARATOR } from './constants';\nimport { getBucketId } from './get-bucket-id';\nimport { assertStorageKeyInput } from './key';\n\nexport const encode = (key: Key | null): Key => {\n if (key === null) return null;\n const [fileApi, path] = assertStorageKeyInput(key);\n return [KEY_PREFIX, getBucketId(fileApi), path].join(KEY_SEPARATOR);\n};\n","import type { Middleware, SWRHook } from 'swr';\n\nimport { encode } from './encode';\n\nexport const middleware: Middleware = (useSWRNext: SWRHook) => {\n return (key, fetcher, config) => {\n if (!fetcher) throw new Error('No fetcher provided');\n return useSWRNext(encode(key), () => fetcher(key), config);\n };\n};\n","type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T; // from lodash\n\nexport function truthy<T>(value: T): value is Truthy<T> {\n return !!value;\n}\n","import {\n createRemoveDirectoryFetcher,\n mutatePaths,\n} from '@supabase-cache-helpers/storage-core';\nimport type { FileObject, StorageError } from '@supabase/storage-js';\nimport { useCallback } from 'react';\nimport { type Key, useSWRConfig } from 'swr';\nimport useSWRMutation, {\n type SWRMutationResponse,\n type SWRMutationConfiguration,\n} from 'swr/mutation';\n\nimport { type StorageFileApi, decode, getBucketId } from '../lib';\nimport { useRandomKey } from './use-random-key';\n\n/**\n * A hook that provides a mutation function to remove a directory and all its contents.\n * @param fileApi The `StorageFileApi` instance to use for the removal.\n * @param config Optional configuration options for the SWR mutation.\n * @returns An object containing the mutation function, loading state, and error state.\n */\nfunction useRemoveDirectory(\n fileApi: StorageFileApi,\n config?: SWRMutationConfiguration<FileObject[], StorageError, string, string>,\n): SWRMutationResponse<FileObject[], StorageError, string, string> {\n const key = useRandomKey();\n const { cache, mutate } = useSWRConfig();\n const fetcher = useCallback(createRemoveDirectoryFetcher(fileApi), [fileApi]);\n return useSWRMutation<FileObject[], StorageError, string, string>(\n key,\n async (_, { arg }) => {\n const result = fetcher(arg);\n await mutatePaths<Key>(getBucketId(fileApi), [arg], {\n cacheKeys: Array.from(cache.keys()),\n decode,\n mutate,\n });\n return result;\n },\n config,\n );\n}\n\nexport { useRemoveDirectory };\n","import { useId } from 'react';\n\nimport { KEY_SEPARATOR } from '../lib';\n\nconst PREFIX = 'random-mutation-key';\n\nexport const useRandomKey = () => {\n const key = useId();\n\n return [PREFIX, key].join(KEY_SEPARATOR);\n};\n","import {\n createRemoveFilesFetcher,\n mutatePaths,\n} from '@supabase-cache-helpers/storage-core';\nimport type { FileObject, StorageError } from '@supabase/storage-js';\nimport { useCallback } from 'react';\nimport { type Key, useSWRConfig } from 'swr';\nimport useSWRMutation, {\n type SWRMutationResponse,\n type SWRMutationConfiguration,\n} from 'swr/mutation';\n\nimport { type StorageFileApi, decode, getBucketId } from '../lib';\nimport { useRandomKey } from './use-random-key';\n\n/**\n * Hook for removing files from storage using SWR mutation\n * @param {StorageFileApi} fileApi - The Supabase Storage API\n * @param {SWRMutationConfiguration<FileObject[], StorageError, string[], string>} [config] - The SWR mutation configuration\n * @returns {SWRMutationResponse<FileObject[], StorageError, string[], string>} - The SWR mutation response object\n */\nfunction useRemoveFiles(\n fileApi: StorageFileApi,\n config?: SWRMutationConfiguration<\n FileObject[],\n StorageError,\n string,\n string[]\n >,\n): SWRMutationResponse<FileObject[], StorageError, string, string[]> {\n const key = useRandomKey();\n const { cache, mutate } = useSWRConfig();\n const fetcher = useCallback(createRemoveFilesFetcher(fileApi), [fileApi]);\n return useSWRMutation<FileObject[], StorageError, string, string[]>(\n key,\n async (_, { arg: paths }) => {\n const res = await fetcher(paths);\n await mutatePaths<Key>(getBucketId(fileApi), paths, {\n cacheKeys: Array.from(cache.keys()),\n decode,\n mutate,\n });\n return res;\n },\n config,\n );\n}\n\nexport { useRemoveFiles };\n","import {\n type FileInput,\n type UploadFetcherConfig,\n type UploadFileResponse,\n createUploadFetcher,\n mutatePaths,\n} from '@supabase-cache-helpers/storage-core';\nimport type { StorageError } from '@supabase/storage-js';\nimport { useCallback } from 'react';\nimport { useSWRConfig } from 'swr';\nimport useSWRMutation, {\n type SWRMutationResponse,\n type SWRMutationConfiguration,\n} from 'swr/mutation';\n\nimport { type StorageFileApi, decode, getBucketId, truthy } from '../lib';\nimport { useRandomKey } from './use-random-key';\n\nexport type { UploadFetcherConfig, UploadFileResponse, FileInput };\n\n/**\n * The input object for the useUpload mutation function.\n * @typedef {Object} UseUploadInput\n * @property {FileList|(File|FileInput)[]} files - The file(s) to be uploaded\n * @property {string} [path] - The path in the storage bucket to upload the file(s) to\n */\nexport type UseUploadInput = {\n files: FileList | (File | FileInput)[];\n path?: string;\n};\n\n/**\n * Hook for uploading files to storage using SWR mutation\n * @param {StorageFileApi} fileApi - The Supabase Storage API\n * @param {UploadFetcherConfig & SWRMutationConfiguration<UploadFileResponse[], StorageError, UseUploadInput, string>} [config] - The SWR mutation configuration\n * @returns {SWRMutationResponse<UploadFileResponse[], StorageError, UseUploadInput, string>} - The SWR mutation response object\n */\nfunction useUpload(\n fileApi: StorageFileApi,\n config?: UploadFetcherConfig &\n SWRMutationConfiguration<\n UploadFileResponse[],\n StorageError,\n string,\n UseUploadInput\n >,\n): SWRMutationResponse<\n UploadFileResponse[],\n StorageError,\n string,\n UseUploadInput\n> {\n const key = useRandomKey();\n const { cache, mutate } = useSWRConfig();\n const fetcher = useCallback(createUploadFetcher(fileApi, config), [\n config,\n fileApi,\n ]);\n return useSWRMutation<\n UploadFileResponse[],\n StorageError,\n string,\n UseUploadInput\n >(\n key,\n async (_, { arg: { files, path } }) => {\n const result = await fetcher(files, path);\n await mutatePaths(\n getBucketId(fileApi),\n result.map(({ data }) => data?.path).filter(truthy),\n {\n cacheKeys: Array.from(cache.keys()),\n decode,\n mutate,\n },\n );\n return result;\n },\n config,\n );\n}\n\nexport { useUpload };\n","import {\n type StoragePrivacy,\n type URLFetcherConfig,\n createDirectoryUrlsFetcher,\n} from '@supabase-cache-helpers/storage-core';\nimport type { FileObject, StorageError } from '@supabase/storage-js';\nimport useSWR, { type SWRConfiguration, type SWRResponse } from 'swr';\n\nimport { type StorageFileApi, type StorageKeyInput, middleware } from '../lib';\n\n/**\n * Convenience hook to fetch all files in a directory, and their corresponding URLs, from Supabase Storage using SWR.\n *\n * @param {StorageFileApi} fileApi - The file API of the storage bucket.\n * @param {string|null} path - The path of the directory to fetch files from.\n * @param {StoragePrivacy} mode - The privacy mode of the bucket to fetch files from.\n * @param {SWRConfiguration & Pick<URLFetcherConfig, 'expiresIn'>} [config] - Optional SWR configuration and `expiresIn` value to pass to the `createDirectoryUrlsFetcher` function.\n *\n * @returns {SWRResponse<(FileObject & { url: string })[] | undefined, StorageError>} An SWR response containing an array of file objects with their corresponding URLs.\n */\nfunction useDirectoryFileUrls(\n fileApi: StorageFileApi,\n path: string | null,\n mode: StoragePrivacy,\n config?: SWRConfiguration<\n (FileObject & { url: string })[] | undefined,\n StorageError\n > &\n Pick<URLFetcherConfig, 'expiresIn'>,\n): SWRResponse<(FileObject & { url: string })[] | undefined, StorageError> {\n return useSWR<(FileObject & { url: string })[] | undefined, StorageError>(\n path ? [fileApi, path] : null,\n ([fileApi, path]: StorageKeyInput) =>\n createDirectoryUrlsFetcher(mode, config)(fileApi, path),\n {\n ...config,\n use: [...(config?.use ?? []), middleware],\n },\n );\n}\n\nexport { useDirectoryFileUrls };\n","import { fetchDirectory } from '@supabase-cache-helpers/storage-core';\nimport type { FileObject, StorageError } from '@supabase/storage-js';\nimport useSWR, { type SWRConfiguration, type SWRResponse } from 'swr';\n\nimport { type StorageFileApi, type StorageKeyInput, middleware } from '../lib';\n\n/**\n * Convenience hook to fetch a directory from Supabase Storage using SWR.\n *\n * @param fileApi The StorageFileApi instance.\n * @param path The path to the directory.\n * @param config The SWR configuration.\n * @returns An SWRResponse containing an array of FileObjects\n */\nfunction useDirectory(\n fileApi: StorageFileApi,\n path: string | null,\n config?: SWRConfiguration<FileObject[] | undefined, StorageError>,\n): SWRResponse<FileObject[] | undefined, StorageError> {\n return useSWR<FileObject[] | undefined, StorageError>(\n path ? [fileApi, path] : null,\n ([fileApi, path]: StorageKeyInput) => fetchDirectory(fileApi, path),\n {\n ...config,\n use: [...(config?.use ?? []), middleware],\n },\n );\n}\n\nexport { useDirectory };\n","import {\n type StoragePrivacy,\n type URLFetcherConfig,\n createUrlFetcher,\n} from '@supabase-cache-helpers/storage-core';\nimport type { StorageError } from '@supabase/storage-js';\nimport useSWR, { type SWRConfiguration, type SWRResponse } from 'swr';\n\nimport { type StorageFileApi, type StorageKeyInput, middleware } from '../lib';\n\n/**\n * A hook to fetch the URL for a file in the Storage.\n *\n * @param fileApi - the file API instance from the Supabase client.\n * @param path - the path of the file to fetch the URL for.\n * @param mode - the privacy mode of the bucket the file is in.\n * @param config - the SWR configuration options and URL fetcher configuration.\n * @returns the SWR response for the URL of the file\n */\nfunction useFileUrl(\n fileApi: StorageFileApi,\n path: string | null,\n mode: StoragePrivacy,\n config?: SWRConfiguration<string | undefined, StorageError> &\n URLFetcherConfig,\n): SWRResponse<string | undefined, StorageError> {\n return useSWR<string | undefined, StorageError>(\n path ? [fileApi, path] : null,\n ([fileApi, path]: StorageKeyInput) =>\n createUrlFetcher(mode, config)(fileApi, path),\n {\n ...config,\n use: [...(config?.use ?? []), middleware],\n },\n );\n}\n\nexport { useFileUrl };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,aAAa;AACnB,IAAM,gBAAgB;;;ACItB,IAAM,SAAS,CAAC,QAAuC;AAC5D,MAAI,OAAO,QAAQ,YAAY,CAAC,IAAI,WAAW,UAAU,EAAG,QAAO;AACnE,QAAM,CAAC,GAAG,UAAU,IAAI,IAAI,IAAI,MAAM,aAAa;AACnD,SAAO,EAAE,UAAU,KAAK;AAC1B;;;ACPO,IAAM,cAAc,CAAC,YAC1B,QAAQ,UAAU;;;ACCb,IAAM,oBAAoB,CAAC,QAChC,MAAM,QAAQ,GAAG,KACjB,IAAI,WAAW,KACf,OAAO,IAAI,CAAC,MAAM,YAClB,QAAQ,IAAI,CAAC,EAAE,UAAU,CAAC;AAErB,IAAM,wBAAwB,CAAC,QAA8B;AAClE,MAAI,CAAC,kBAAkB,GAAG,EAAG,OAAM,I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O;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;;;AChFA,IAAAC,uBAIO;AAEP,IAAAC,cAAgE;AAchE,SAAS,qBACP,SACA,MACA,MACA,QAKyE;AA7B3E;AA8BE,aAAO,YAAAC;AAAA,IACL,OAAO,CAAC,SAAS,IAAI,IAAI;AAAA,IACzB,CAAC,CAACC,UAASC,KAAI,UACb,iDAA2B,MAAM,MAAM,EAAED,UAASC,KAAI;AAAA,IACxD,iCACK,SADL;AAAA,MAEE,KAAK,CAAC,IAAI,sCAAQ,QAAR,YAAe,CAAC,GAAI,UAAU;AAAA,IAC1C;AAAA,EACF;AACF;;;ACvCA,IAAAC,uBAA+B;AAE/B,IAAAC,cAAgE;AAYhE,SAAS,aACP,SACA,MACA,QACqD;AAlBvD;AAmBE,aAAO,YAAAC;AAAA,IACL,OAAO,CAAC,SAAS,IAAI,IAAI;AAAA,IACzB,CAAC,CAACC,UAASC,KAAI,UAAuB,qCAAeD,UAASC,KAAI;AAAA,IAClE,iCACK,SADL;AAAA,MAEE,KAAK,CAAC,IAAI,sCAAQ,QAAR,YAAe,CAAC,GAAI,UAAU;AAAA,IAC1C;AAAA,EACF;AACF;;;AC3BA,IAAAC,uBAIO;AAEP,IAAAC,cAAgE;AAahE,SAAS,WACP,SACA,MACA,MACA,QAE+C;AAzBjD;AA0BE,aAAO,YAAAC;AAAA,IACL,OAAO,CAAC,SAAS,IAAI,IAAI;AAAA,IACzB,CAAC,CAACC,UAASC,KAAI,UACb,uCAAiB,MAAM,MAAM,EAAED,UAASC,KAAI;AAAA,IAC9C,iCACK,SADL;AAAA,MAEE,KAAK,CAAC,IAAI,sCAAQ,QAAR,YAAe,CAAC,GAAI,UAAU;AAAA,IAC1C;AAAA,EACF;AACF;","names":["import_react","useSWRMutation","import_storage_core","import_react","import_swr","import_mutation","useSWRMutation","import_storage_core","import_react","import_swr","import_mutation","useSWRMutation","import_storage_core","import_swr","useSWR","fileApi","path","import_storage_core","import_swr","useSWR","fileApi","path","import_storage_core","import_swr","useSWR","fileApi","path"]}