Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial file storage support #52

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions packages/ra-supabase-core/src/dataProvider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DataProvider, fetchUtils } from 'ra-core';
import { DataProvider, fetchUtils, withLifecycleCallbacks } from 'ra-core';
import postgrestRestProvider, {
IDataProviderConfig,
defaultPrimaryKeys,
Expand All @@ -24,10 +24,19 @@ export const supabaseDataProvider = ({
defaultListOp = 'eq',
primaryKeys = defaultPrimaryKeys,
schema = defaultSchema,
storagePath,
filenameFromData = ({ filename }) => filename,
}: {
instanceUrl: string;
apiKey: string;
supabaseClient: SupabaseClient;
storagePath?: string | ((resource: string) => string);
filenameFromData?: (_: {
data: string;
resource: string;
field: string;
filename: string;
}) => string;
} & Partial<Omit<IDataProviderConfig, 'apiUrl'>>): DataProvider => {
const config: IDataProviderConfig = {
apiUrl: `${instanceUrl}/rest/v1`,
Expand All @@ -36,7 +45,50 @@ export const supabaseDataProvider = ({
primaryKeys,
schema,
};
return postgrestRestProvider(config);
return withLifecycleCallbacks(postgrestRestProvider(config), [
Copy link
Contributor

@adguernier adguernier Feb 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

polish: We should provide some customization to users who use this library. This implementation does not allow this.

See this PR discussion for more information.

{
resource: '*',
beforeSave: async (
data: any,
dataProvider: DataProvider,
resource: string
) => {
if (!storagePath) return data;
const newFiles = (
await Promise.all(
Object.keys(data)
.filter(key => data[key]?.rawFile instanceof File)
.map(async (key: string) => {
const file = data[key];
const bucket =
storagePath instanceof Function
? storagePath(resource)
: storagePath;
const filename = filenameFromData({
data,
resource,
field: key,
filename: file.rawFile.name,
});

const { error } = await supabaseClient.storage
.from(bucket)
.upload(filename, file.rawFile);
if (error) throw error;
const {
data: { publicUrl },
} = supabaseClient.storage
.from(bucket)
.getPublicUrl(filename);

return { [key]: publicUrl };
})
)
).reduce((acc, val) => ({ ...acc, ...val }), {});
return { ...data, ...newFiles };
},
},
]);
};

/**
Expand Down