Last active
July 12, 2022 17:59
-
-
Save polluterofminds/bb205cdf08a86ac6bdd91669270b36dc to your computer and use it in GitHub Desktop.
Token Gated Media Upload
This file contains hidden or 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 { getSession } from "next-auth/react"; | |
import formidable from "formidable"; | |
import fs from "fs"; | |
import { Submarine } from "pinata-submarine"; | |
const submarine = new Submarine(process.env.SUBMARINE_KEY, process.env.GATEWAY_URL); | |
const IDENTIFIER = "YOUR UNIQUE ID"; | |
export const config = { | |
api: { | |
bodyParser: false, | |
}, | |
}; | |
const getIndex = async (limit=10, offset=0) => { | |
try { | |
const options = { | |
metadata: JSON.stringify({ | |
uuid: { | |
value: IDENTIFIER, | |
op: "eq" | |
} | |
}), | |
offset, | |
limit | |
} | |
const contentIndex = await submarine.getSubmarinedContent(options); | |
return contentIndex; | |
} catch (error) { | |
throw error; | |
} | |
}; | |
const saveFile = async (file) => { | |
try { | |
const metadata = { | |
uuid: IDENTIFIER, | |
}; | |
await submarine.uploadFileOrFolder(file.filepath, file.original_name, metadata, 1); | |
fs.unlinkSync(file.filepath); | |
return; | |
} catch (error) { | |
throw error; | |
} | |
}; | |
export default async function handler(req, res) { | |
const session = await getSession({ req }); | |
if (req.method === "POST") { | |
try { | |
if (!session) { | |
return res.status(401).send("Not signed in"); | |
} | |
const form = new formidable.IncomingForm(); | |
form.parse(req, async function (err, fields, files) { | |
if (err) { | |
console.log({ err }); | |
throw err; | |
} | |
await saveFile(files.file); | |
return res.status(201).send("Success"); | |
}); | |
} catch (error) { | |
console.log(error); | |
res.status(500).send("Server error"); | |
} | |
} else { | |
try { | |
if (!session) { | |
return res.status(401).send("Not signed in"); | |
} | |
const indexFile = await getIndex(); | |
res.status(200).json({ index: indexFile }); | |
} catch (error) { | |
console.log(error); | |
res.status(500).send("Server error"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment