-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
148 lines (131 loc) · 4.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const rateLimit = require("express-rate-limit");
const axios = require("axios");
const FormData = require("form-data");
const app = express();
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const mime = require("mime");
const PORT = process.env.PORT || 3001;
// Rate limiting
const limiter = rateLimit({
max: 40,
windowMs: 60 * 60 * 1000,
message: "Too many requests from this IP address",
});
app.set("trust proxy", 1);
app.use(express.json());
app.use(limiter);
app.use(cors());
// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, "./client/build")));
const uploadDirectory = path.join(__dirname, "/uploads/");
// ensure that the directory exits
if (!fs.existsSync(uploadDirectory)) {
fs.mkdirSync(uploadDirectory);
}
// Set up storage for uploaded files
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDirectory);
},
filename: (req, file, cb) => {
cb(null, `${file.fieldname}-${Date.now()}-${file.originalname}`);
},
});
// Create the multer instance
const upload = multer({
storage: storage,
limits: { fileSize: 10 * 1024 * 1024 }, // 10mb max size
fileFilter: (req, file, cb) => {
if (
file.mimetype.startsWith("image/") ||
file.mimetype === "application/pdf" ||
file.mimetype === "text/plain" ||
file.mimetype === "application/msword" ||
file.mimetype ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
file.mimetype === "application/epub+zip"
) {
cb(null, true); //accept the file
} else {
// Reject the file
cb(new multer.MulterError("LIMIT_UNEXPECTED_FILE"), false);
}
},
}).single("file");
app.post("/api/upload", async (req, res) => {
upload(req, res, function (err) {
// if (!req.file) {
// return res.status(400).send({ message: "No file was uploaded." });
// }
if (err instanceof multer.MulterError) {
let message = "An error occurred when uploading.";
if (err.code === "LIMIT_FILE_SIZE") {
message = "File size exceeds the limit. Max-size: 10MB";
}
if (err.code === "LIMIT_UNEXPECTED_FILE") {
message = "Invalid file type!";
}
return res.status(400).send({ message });
} else if (err) {
// Handle custom errors or other errors here.
return res
.status(500)
.send({ message: err.message || "A server error occurred." });
} else {
const file = req.file;
const body = req.body;
console.log("File is: ", file);
const data = new FormData();
const fileStream = fs.createReadStream(file.path);
data.append("file", fileStream);
// Optional parameters
const metadata = JSON.stringify({
name: file.originalname,
});
data.append("pinataMetadata", metadata);
const options = JSON.stringify({
cidVersion: 0,
});
data.append("pinataOptions", options);
axios
.post("https://api.pinata.cloud/pinning/pinFileToIPFS", data, {
maxBodyLength: Infinity,
headers: {
"Content-Type": `multipart/form-data; boundary=${data._boundary}`,
Authorization: `Bearer ${process.env.PINATA_JWT}`,
},
})
.then((pinataResponse) => {
console.log(pinataResponse.data);
const mimeType = mime.getType(file.path);
const fileName = file.originalname
const response = {
IpfsHash: pinataResponse.data.IpfsHash,
PinSize: pinataResponse.data.PinSize,
Timestamp: pinataResponse.data.Timestamp,
MimeType: mimeType,
FileName: fileName
};
res.status(200).send(response);
})
.catch((error) => {
console.log("Error pinning file to IPFS:", error.message);
return res
.status(500)
.send({ message: "Error pinning file to IPFS" });
});
};
})
});
// All other request not handled by api will return the react app
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, './client/build', 'index.html'))
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});