1
0
Fork 0
mirror of https://github.com/SunRed/haste-server.git synced 2024-11-01 01:30:21 +01:00

Made server run async

This commit is contained in:
zneix 2020-08-27 00:39:06 +02:00
parent 78aabf90bb
commit f3288c4e39
3 changed files with 28 additions and 23 deletions

View file

@ -14,8 +14,8 @@ const DocumentHandler = function(options) {
DocumentHandler.defaultKeyLength = 10; DocumentHandler.defaultKeyLength = 10;
// Handle retrieving a document // Handle retrieving a document
DocumentHandler.prototype.handleGet = function(key, res, skipExpire) { DocumentHandler.prototype.handleGet = async function(key, res, skipExpire) {
this.store.get(key, function(ret) { await this.store.get(key, function(ret) {
if (ret) { if (ret) {
winston.verbose('retrieved document', { key: key }); winston.verbose('retrieved document', { key: key });
res.writeHead(200, { 'content-type': 'application/json' }); res.writeHead(200, { 'content-type': 'application/json' });
@ -30,8 +30,8 @@ DocumentHandler.prototype.handleGet = function(key, res, skipExpire) {
}; };
// Handle retrieving the raw version of a document // Handle retrieving the raw version of a document
DocumentHandler.prototype.handleGetRaw = function(key, res, skipExpire) { DocumentHandler.prototype.handleGetRaw = async function(key, res, skipExpire) {
this.store.get(key, function(ret) { await this.store.get(key, function(ret) {
if (ret) { if (ret) {
winston.verbose('retrieved raw document', { key: key }); winston.verbose('retrieved raw document', { key: key });
res.writeHead(200, { 'content-type': 'text/plain; charset=UTF-8' }); res.writeHead(200, { 'content-type': 'text/plain; charset=UTF-8' });
@ -46,13 +46,13 @@ DocumentHandler.prototype.handleGetRaw = function(key, res, skipExpire) {
}; };
// Handle adding a new Document // Handle adding a new Document
DocumentHandler.prototype.handlePost = function (req, res) { DocumentHandler.prototype.handlePost = async function (req, res) {
let _this = this; let _this = this;
let buffer = ''; let buffer = '';
let cancelled = false; let cancelled = false;
// What to do when done // What to do when done
let onSuccess = function () { let onSuccess = async function () {
// Check length // Check length
if (_this.maxLength && buffer.length > _this.maxLength) { if (_this.maxLength && buffer.length > _this.maxLength) {
cancelled = true; cancelled = true;
@ -64,8 +64,8 @@ DocumentHandler.prototype.handlePost = function (req, res) {
return; return;
} }
// And then save if we should // And then save if we should
_this.chooseKey(function (key) { await _this.chooseKey(async function (key) {
_this.store.set(key, buffer, function (resp) { await _this.store.set(key, buffer, function (resp) {
if (resp) { if (resp) {
winston.verbose('added document', { key: key }); winston.verbose('added document', { key: key });
res.writeHead(200, { 'content-type': 'application/json' }); res.writeHead(200, { 'content-type': 'application/json' });
@ -89,8 +89,8 @@ DocumentHandler.prototype.handlePost = function (req, res) {
buffer = val; buffer = val;
} }
}); });
busboy.on('finish', function () { busboy.on('finish', async function () {
onSuccess(); await onSuccess();
}); });
req.pipe(busboy); req.pipe(busboy);
// Otherwise, use our own and just grab flat data from POST body // Otherwise, use our own and just grab flat data from POST body
@ -98,9 +98,9 @@ DocumentHandler.prototype.handlePost = function (req, res) {
req.on('data', function (data) { req.on('data', function (data) {
buffer += data.toString(); buffer += data.toString();
}); });
req.on('end', function () { req.on('end', async function () {
if (cancelled) { return; } if (cancelled) { return; }
onSuccess(); await onSuccess();
}); });
req.on('error', function (error) { req.on('error', function (error) {
winston.error('connection error: ' + error.message); winston.error('connection error: ' + error.message);
@ -112,10 +112,10 @@ DocumentHandler.prototype.handlePost = function (req, res) {
}; };
// Keep choosing keys until one isn't taken // Keep choosing keys until one isn't taken
DocumentHandler.prototype.chooseKey = function(callback) { DocumentHandler.prototype.chooseKey = async function(callback) {
let key = this.acceptableKey(); let key = this.acceptableKey();
let _this = this; let _this = this;
this.store.get(key, function(ret) { await this.store.get(key, function(ret) {
if (ret) { if (ret) {
_this.chooseKey(callback); _this.chooseKey(callback);
} else { } else {

View file

@ -46,7 +46,7 @@ FileDocumentStore.prototype.set = function(key, data, callback, skipExpire) {
// Get data from a file from key // Get data from a file from key
FileDocumentStore.prototype.get = function(key, callback, skipExpire) { FileDocumentStore.prototype.get = function(key, callback, skipExpire) {
const _this = this; const _this = this;
const fn = this.basePath + '/' + FileDocumentStore.md5(key); const fn = require('path').join(this.basePath, FileDocumentStore.md5(key));
fs.readFile(fn, 'utf8', function(err, data) { fs.readFile(fn, 'utf8', function(err, data) {
if (err) { if (err) {
callback(false); callback(false);

View file

@ -59,13 +59,16 @@ if (config.recompressStaticAssets){
winston.info(`compressed ${file} into ${dest}`); winston.info(`compressed ${file} into ${dest}`);
} }
} }
(async function(){
//send the static documents into the preferred store, skipping expirations //send the static documents into the preferred store, skipping expirations
for (const name in config.documents){ for (const name in config.documents){
let path = config.documents[name]; let path = config.documents[name];
winston.info('loading static document', { name: name, path: path }); winston.info('loading static document', { name: name, path: path });
let data = fs.readFileSync(path, 'utf8'); let data = fs.readFileSync(path, 'utf8');
if (data){ if (data){
preferredStore.set(name, data, doc => winston.debug('loaded static document', { success: doc }), true); await preferredStore.set(name, data, doc => winston.debug('loaded static document', { success: doc }), true);
} }
else { else {
winston.warn('failed to load static document', { name: name, path: path }); winston.warn('failed to load static document', { name: name, path: path });
@ -92,22 +95,22 @@ if (config.rateLimits) app.use(expressRateLimit(config.rateLimits));
//try API first //try API first
//get raw documents //get raw documents
app.get('/raw/:id', (req, res) => { app.get('/raw/:id', async (req, res) => {
const key = req.params.id.split('.')[0]; const key = req.params.id.split('.')[0];
const skipExpire = Boolean(config.documents[key]); const skipExpire = Boolean(config.documents[key]);
return documentHandler.handleGetRaw(key, res, skipExpire); return await documentHandler.handleGetRaw(key, res, skipExpire);
}); });
//add documents //add documents
app.post('/documents', (req, res) => { app.post('/documents', async (req, res) => {
return documentHandler.handlePost(req, res); return await documentHandler.handlePost(req, res);
}); });
//get documents //get documents
app.get('/documents/:id', (req, res) => { app.get('/documents/:id', async (req, res) => {
const key = req.params.id.split('.')[0]; const key = req.params.id.split('.')[0];
const skipExpire = Boolean(config.documents[key]); const skipExpire = Boolean(config.documents[key]);
return documentHandler.handleGet(key, res, skipExpire); return await documentHandler.handleGet(key, res, skipExpire);
}); });
//try static next //try static next
@ -131,4 +134,6 @@ app.use(st({
index: 'index.html' index: 'index.html'
})); }));
app.listen(config.port, config.host, () => winston.info(`listening on ${config.host}:${config.port}`)); app.listen(config.port, config.host, () => winston.info(`listening on ${config.host}:${config.port}`));
})();