Skip to content

Instantly share code, notes, and snippets.

@MarkAtOmniux
Created March 26, 2023 15:17
Show Gist options
  • Save MarkAtOmniux/27106a14102a108ae13eeeff30da6c19 to your computer and use it in GitHub Desktop.
Save MarkAtOmniux/27106a14102a108ae13eeeff30da6c19 to your computer and use it in GitHub Desktop.
Example of a custom BeforeDashboard React Component that displays the total amount of storage space left in a Google Cloud Bucket
import React, { useEffect, useState } from 'react'
import * as gcs from '@google-cloud/storage';
const SpaceRemaining = () => {
const [totalBytes, setTotalBytes] = useState(null);
const [limitBytes, setLimitBytes] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchBucketInfo = async () => {
console.log('fetch bucket')
try {
const storage = new gcs.Storage({
projectId: 'my-project',
});
const bucket = storage.bucket('my-project-bucket');
const [metadata] = await bucket.getMetadata();
setTotalBytes(metadata.usage);
if (metadata.storageClass.locationType === 'multi-region') {
setLimitBytes(metadata.storageClass.multiRegionalLocationObjectThresholds[0].threshold);
} else {
setLimitBytes(metadata.storageClass.regionalLocationObjectThresholds[0].threshold);
}
} catch (err) {
setError(err.message);
}
};
fetchBucketInfo();
}, [])
const getStorageUsage = () => {
if (error) {
return <p>Error retrieving bucket info: {error}</p>;
} else if (totalBytes === null || limitBytes === null) {
return <p>Loading...</p>;
} else {
return (
<>
<p>Total storage used: {totalBytes} bytes</p>
<p>Remaining storage: {limitBytes - totalBytes} bytes</p>
</>
);
}
}
return (
<div>
<h4>Space Remaining</h4>
{getStorageUsage()}
</div>
)
}
export default SpaceRemaining
import { buildConfig } from 'payload/config';
import path from 'path';
import Users from './collections/Users';
import SpaceRemaining from './components/SpaceRemaining';
export default buildConfig({
serverURL: process.env.PAYLOAD_PUBLIC_PAYLOAD_URL,
admin: {
user: Users.slug,
components: {
beforeDashboard: [SpaceRemaining]
},
webpack: (config) => ({
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
react: path.resolve(__dirname, '../node_modules/react'),
'react-dom': path.resolve(__dirname, '../node_modules/react-dom'),
'react-router-dom': path.resolve(__dirname, '../node_modules/react-router-dom'),
}
}
})
},
collections: [
Users,
],
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
graphQL: {
schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment