@needle-tools/networking
Version:
Networking backend functionality for Needle Engine
80 lines (69 loc) • 2.04 kB
JavaScript
const DiscStorage = require("./storage/discStorage");
const { tryCreateS3Storage } = require("./storage/s3Storage");
const discStorage = new DiscStorage(".data/rooms");
const s3 = tryCreateS3Storage();
/**
* @param {string} roomName
* @returns
*/
module.exports.loadRoomState = async function (roomName) {
if (s3) {
return s3.loadRoomState(roomName);
}
return discStorage.loadRoomState(roomName);;
};
/**
* @param {string} roomName
* @param {any} state
*/
module.exports.saveRoomState = async function (roomName, state) {
if (s3) {
return s3.saveRoomState(roomName, state);
}
return discStorage.saveRoomState(roomName, state);
};
class BlobStorage {
/**
* @param {{content_md5:string, key:string, content_type:string, content_length:number, filename:string}} data
* @returns {Promise<{error:string} | { key:string } | { key:string, upload:string } | null>}
*/
async getUploadURL(data) {
if (!s3) {
return Promise.resolve({ error: "S3 is not configured" });;
}
const { key } = data;
if (!key?.length) {
return Promise.resolve({ error: "no key" });
}
const s3Key = "blobs/" + key;
const exists = await s3.blobExists(s3Key).catch(e => { console.error(e); return false; });
if (exists) {
return Promise.resolve({
key: s3Key,
});
}
return s3.getUploadURL(s3Key, data).then(res => {
if (typeof res === "string") {
return {
upload: res,
key: key
};
}
return res;
})
}
/**
* @param {string} key
* @returns {Promise<string | {error:string}>} the presigned url if successful
*/
async getDownloadURL(key) {
if (!s3) {
return Promise.resolve({ error: "S3 is not configured" });;
}
else if(!key.length){
return Promise.resolve({ error : "no key" });
}
return s3.getDownloadURL("blobs/" + key);
}
}
module.exports.blobStorage = new BlobStorage();