bin/helpers/content/index.js

51 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-03-04 02:31:07 +01:00
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
2023-03-04 06:00:53 +01:00
const glob = require('glob');
2023-03-04 02:31:07 +01:00
const root = path.join(process.cwd(), '/usercontent');
2023-03-04 06:00:53 +01:00
const { MAXFILES } = process.env;
2023-03-04 06:52:51 +01:00
// console.log(root);
2023-03-04 06:00:53 +01:00
let initalized = false;
let submitted = 0;
async function init() {
if (initalized) return;
2023-03-04 06:52:51 +01:00
let files = await glob(root + '/*');
files.filter(file => {return !file.startsWith('.')})
.forEach(file => {
2023-03-04 06:00:53 +01:00
submitted++;
2023-03-04 06:52:51 +01:00
return;
2023-03-04 06:00:53 +01:00
});
}
2023-03-04 06:52:51 +01:00
init();
2023-03-04 06:00:53 +01:00
2023-03-04 06:52:51 +01:00
function get_submitted() {return submitted;}
2023-03-04 06:00:53 +01:00
2023-03-04 02:31:07 +01:00
const make_id = () => {
return crypto.randomBytes(8).toString('hex');
};
async function get(id) {
2023-03-04 06:00:53 +01:00
init();
2023-03-04 02:39:59 +01:00
return fs.readFileSync(path.join(root, id)).toString();
2023-03-04 02:31:07 +01:00
}
async function write(fname, data) {
2023-03-04 06:00:53 +01:00
init();
submitted++;
2023-03-04 02:39:59 +01:00
return fs.writeFile(path.join(root, fname), data, () => {});
2023-03-04 02:31:07 +01:00
}
async function create(data) {
2023-03-04 06:00:53 +01:00
if (submitted >= MAXFILES) return "NA";
2023-03-04 02:31:07 +01:00
const id = make_id();
2023-03-04 02:39:59 +01:00
await write(id, data);
2023-03-04 02:31:07 +01:00
return id;
}
2023-03-04 06:52:51 +01:00
module.exports = { get, write, create, make_id, submitted: get_submitted, init };