Created
July 16, 2024 07:38
-
-
Save martincik/334008ba59da51f963f9945fbbcd5125 to your computer and use it in GitHub Desktop.
Iris SDK upload via Node.js Express and Multer extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express, { Application, Request, Response } from 'express'; | |
import cors from 'cors'; | |
import multer from "multer"; | |
import fs from "fs"; | |
import Irys from '@irys/sdk'; | |
import { env } from '@/env'; | |
const app: Application = express(); | |
const upload = multer({ dest: './uploads' }) | |
app.use(cors()); | |
app.use(express.json({ limit: '305mb' })); | |
app.get('/health', (_req: Request, res: Response) => { | |
res.send('OK'); | |
}); | |
app.post('/upload', upload.single('file'), async (req: Request, res: Response) => { | |
const file = req.file; | |
if (!file) { | |
res.status(403).send('No file uploaded.'); | |
return; | |
} | |
try { | |
const irys = new Irys({ | |
network: "mainnet", // "mainnet" || "devnet" | |
token: "aptos", | |
key: env.PRIVATE_KEY_STRING | |
}); | |
const fileStream = fs.createReadStream(file.path); | |
const price = await irys.getPrice(file.size); | |
console.log(`Uploading Image to Arweave: ${file.path} - Size: ${file.size} - Price: ${price}`); | |
await irys.fund(price); | |
const receipt = await irys.upload(fileStream, { | |
tags: [{ name: "Content-Type", value: file.mimetype }], | |
}); | |
const imgUri = `https://arweave.net/${receipt.id}` | |
console.log(`Image URI: ${imgUri}`); | |
res.send(imgUri); | |
} catch (e) { | |
console.error(e); | |
res.status(500).send(e instanceof Error ? `Error: ${e.message}` : 'Something went wrong'); | |
} finally { | |
try { | |
fs.promises.unlink(file.path); | |
} catch (err) { | |
console.error(`Error while deleting the file: ${err}`); | |
} | |
} | |
res.end(); | |
}); | |
app.listen(env.PORT, function () { | |
console.log(`Sketch API is listening on port ${env.PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment