Skip to content

Instantly share code, notes, and snippets.

@iRoachie
Created May 9, 2023 13:23
Show Gist options
  • Save iRoachie/e6b19819809b1edb6c99a51eb6cff1f0 to your computer and use it in GitHub Desktop.
Save iRoachie/e6b19819809b1edb6c99a51eb6cff1f0 to your computer and use it in GitHub Desktop.
S3 presigner and upload
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { createRouter } from 'next-connect';
import type { NextApiRequest, NextApiResponse } from 'next';
import { config as appConfig } from '../../../config';
import { apiHandler, hasRequiredScopes } from '../../../util/util';
const { aws } = appConfig;
const s3 = new S3Client({
region: aws.config.region,
credentials: {
accessKeyId: aws.config.access_key,
secretAccessKey: aws.config.secret_access_key,
},
});
const router = createRouter<NextApiRequest, NextApiResponse>();
router.post(async (req, res) => {
await hasRequiredScopes(req, res, ['manage:client-entities']);
let { name, type } = req.body;
const command = new PutObjectCommand({
Bucket: aws.supportingDocumentsBucket,
Key: name,
ContentType: type,
});
const url = await getSignedUrl(s3, command, { expiresIn: 1000 });
res.status(200).json({ url });
});
export default apiHandler(router);
import axios from 'axios';
const client = axios.create({
baseURL: '/api/s3',
});
const uploadFile = async (file: File, url: string) => {
await fetch(url, {
method: 'PUT',
body: file,
headers: {
'Content-Type': file.type,
'Access-Control-Allow-Origin': '*',
},
});
};
/**
* Upload supporting document directly to s3
*
* @param file
* @returns File uri
*/
export const uploadSupportingDocument = async (file: File) => {
const key = `${Date.now()} - ${file.name}`;
const { data } = await client.post<{ url: string }>(`/supporting-documents`, {
name: key,
type: file.type,
});
await uploadFile(file, data.url);
return key;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment