Move s3 to separate uploader module, add ipfs uploader

This commit is contained in:
Alex Gleason 2023-09-07 16:59:05 -05:00
parent 4622b52f78
commit c4af44d582
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
4 changed files with 65 additions and 17 deletions

View File

@ -1,10 +1,8 @@
import { AppController } from '@/app.ts';
import { Conf } from '@/config.ts';
import { IpfsHash, S3Client, z } from '@/deps.ts';
import { z } from '@/deps.ts';
import { fileSchema } from '@/schema.ts';
import { parseBody } from '@/utils/web.ts';
const s3 = new S3Client({ ...Conf.s3 });
import { s3Uploader } from '@/uploaders/s3.ts';
const mediaBodySchema = z.object({
file: fileSchema.refine((file) => !!file.type),
@ -20,25 +18,18 @@ const mediaController: AppController = async (c) => {
return c.json({ error: 'Bad request.', schema: result.error }, 422);
}
const { file } = result.data;
const cid = await IpfsHash.of(file.stream()) as string;
try {
await s3.putObject(`ipfs/${cid}`, file.stream(), {
metadata: {
'Content-Type': file.type,
'x-amz-acl': 'public-read',
},
const { file } = result.data;
const { cid } = await s3Uploader(file);
return c.json({
id: cid,
type: file.type,
});
} catch (e) {
console.error(e);
return c.json({ error: 'Failed to upload file.' }, 500);
}
return c.json({
id: cid,
type: file.type,
});
};
export { mediaController };

27
src/uploaders/ipfs.ts Normal file
View File

@ -0,0 +1,27 @@
import { z } from '@/deps.ts';
import type { Uploader } from './types.ts';
const ipfsAddResultSchema = z.object({
Name: z.string(),
Hash: z.string(),
Size: z.string(),
});
const ipfsUploader: Uploader = async (file) => {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData,
});
const { Hash } = ipfsAddResultSchema.parse(await response.json());
return {
cid: Hash,
};
};
export { ipfsUploader };

23
src/uploaders/s3.ts Normal file
View File

@ -0,0 +1,23 @@
import { Conf } from '@/config.ts';
import { IpfsHash, S3Client } from '@/deps.ts';
import type { Uploader } from './types.ts';
const s3 = new S3Client({ ...Conf.s3 });
const s3Uploader: Uploader = async (file) => {
const cid = await IpfsHash.of(file.stream()) as string;
await s3.putObject(`ipfs/${cid}`, file.stream(), {
metadata: {
'Content-Type': file.type,
'x-amz-acl': 'public-read',
},
});
return {
cid,
};
};
export { s3Uploader };

7
src/uploaders/types.ts Normal file
View File

@ -0,0 +1,7 @@
interface UploadResult {
cid: string;
}
type Uploader = (file: File) => Promise<UploadResult>;
export type { Uploader, UploadResult };