Skip to content

Commit

Permalink
Update file.js
Browse files Browse the repository at this point in the history
  • Loading branch information
serefyarar committed Oct 31, 2024
1 parent 1a88aea commit 89e3fcb
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions api/src/controllers/file.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,53 @@
import { PinataSDK } from "pinata";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const pinata = new PinataSDK({
pinataJwt: process.env.PINATA_JWT_KEY,
pinataGateway: "ipfs.index.network",
});

const s3Client = new S3Client({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});

export const getAvatar = async (req, res, next) => {
const url = await pinata.gateways.createSignedURL({
cid: req.params.cid,
expires: 30000,
});
return res.redirect(302, url);
};

export const uploadAvatar = async (req, res, next) => {
try {
// Assuming multer is used to handle file uploads and the file is stored temporarily

const file = new File([req.file.buffer], "profilePicture.jpg", {
type: req.file.mimetype,
});

// Upload the file to IPFS via Pinata
const result = await pinata.upload.file(file);
// Upload to IPFS via Pinata
const pinataResult = await pinata.upload.file(file);

// Respond with the IPFS CID
res.json({ cid: result.cid });
// Upload to S3
const s3Params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: `avatars/${pinataResult.cid}.jpg`,
Body: req.file.buffer,
ContentType: req.file.mimetype,
};

await s3Client.send(new PutObjectCommand(s3Params));

// Respond with both IPFS CID and S3 URL
res.json({
cid: pinataResult.cid,
s3: `https://app-static.index.network/avatars/${pinataResult.cid}.jpg`,
});
} catch (error) {
console.error(error);
res.status(500).send("An error occurred while uploading the file to IPFS.");
res.status(500).send("An error occurred while uploading the file.");
}
};

0 comments on commit 89e3fcb

Please sign in to comment.