61 lines
2.3 KiB
JavaScript
61 lines
2.3 KiB
JavaScript
import {PutObjectCommand, S3Client} from "@aws-sdk/client-s3";
|
|
import cors from 'cors'
|
|
import crypto from "crypto";
|
|
|
|
const SNAPSHOT_URL = process.env.DEXORDER_SNAPSHOT_URL;
|
|
const APP_URL = process.env.DEXORDER_APP_URL;
|
|
|
|
const S3_BUCKET = process.env.DEXORDER_SNAPSHOT_S3_BUCKET_NAME;
|
|
const S3_ACCESS_KEY_ID = process.env.DEXORDER_SNAPSHOT_S3_ACCESS_KEY_ID;
|
|
const S3_SECRET_ACCESS_KEY = process.env.DEXORDER_SNAPSHOT_S3_SECRET_ACCESS_KEY;
|
|
const S3_ENDPOINT = process.env.DEXORDER_SNAPSHOT_S3_ENDPOINT; // e.g., 'https://<ACCOUNT_ID>.r2.cloudflarestorage.com/'
|
|
|
|
const s3 = new S3Client({
|
|
region: "auto",
|
|
endpoint: S3_ENDPOINT,
|
|
credentials: {
|
|
accessKeyId: S3_ACCESS_KEY_ID,
|
|
secretAccessKey: S3_SECRET_ACCESS_KEY,
|
|
}
|
|
});
|
|
|
|
|
|
export function initSnapShare(app) {
|
|
// this URL is called by the frontend to upload a snapshot image for use on a share page
|
|
app.put('/snapshot', cors({origin: process.env.DEXORDER_APP_URL}),
|
|
(req, res) => {
|
|
const chunks = [];
|
|
req.on('data', chunk => chunks.push(chunk))
|
|
req.on('error', (err) => res.status(500).send('Error reading body'))
|
|
req.on('end', () => {
|
|
const filename = crypto.randomUUID() + '.png';
|
|
const body = Buffer.concat(chunks);
|
|
s3.send(new PutObjectCommand({
|
|
Bucket: S3_BUCKET,
|
|
Key: filename,
|
|
Body: body,
|
|
ContentType: 'image/png',
|
|
ACL: 'public-read', // or private, depending on your needs
|
|
})).then(sent => {
|
|
res.send(filename)
|
|
}).catch(err => {
|
|
console.log('upload error', err)
|
|
res.status(500).send('error')
|
|
});
|
|
});
|
|
});
|
|
|
|
// this link returns a "share page" that shows the snapshot of the trade setup then redirects
|
|
// to the order page with the trade data loaded from the URL
|
|
app.get('/share', (req, res) => {
|
|
console.log('request', req)
|
|
const imageFilename = req.query.i; // c = snapshot code
|
|
const data = {
|
|
imageUrl: SNAPSHOT_URL + '/' + imageFilename,
|
|
redirectUrl: APP_URL + '/shared?d=' + encodeURIComponent(req.query.d), // d=data
|
|
};
|
|
res.render('share', data);
|
|
});
|
|
|
|
}
|