Skip to content

Instantly share code, notes, and snippets.

@ErisDS
Last active March 22, 2024 16:38
Show Gist options
  • Save ErisDS/559e11bf3e84b89a9594 to your computer and use it in GitHub Desktop.
Save ErisDS/559e11bf3e84b89a9594 to your computer and use it in GitHub Desktop.
HTTP Store, Storage layer for Ghost 0.6.0 - passes images to a HTTP endpoint
var _ = require('lodash'),
fs = require('fs-extra'),
http = require('http'),
path = require('path'),
util = require('util'),
Promise = require('bluebird'),
options = {},
mimeTypes = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.svgz': 'image/svg+xml'
},
mountPoint = 'content/images',
baseStore = require('../../core/server/storage/base');
function HTTPStore(config) {
options = config;
}
util.inherits(HTTPStore, baseStore);
HTTPStore.prototype.save = function (image) {
var targetDir = this.getTargetDir(mountPoint);
return new Promise(function (resolve, reject) {
this.getUniqueFileName(this, image, targetDir).then(function (filename) {
var stream = fs.createReadStream(image.path),
req = http.request(_.extend(options, {
method: 'PUT',
path: filename
}), function (res) {
if (res.statusCode === 201 || res.statusCode === 409) {
resolve(filename);
} else {
reject('Error');
}
});
req.on('error', function (e) {
reject('Error: ' + e);
});
stream.pipe(req);
stream.on('end', function () {
req.end();
});
}).catch(function (err) {
console.error('Error', err);
});
});
};
HTTPStore.prototype.exists = function (filename) {
return new Promise(function (resolve, reject) {
var req = http.request(_.extend(options, {
method: 'HEAD',
path: filename
}), function (res) {
if (res.statusCode === 200) {
resolve(true);
} else if (res.statusCode === 404) {
resolve(false);
} else {
reject('Proxy Error');
}
});
req.on('error', function () {
resolve(false);
});
req.end();
});
};
HTTPStore.prototype.serve = function () {
return function (req, res) {
var getRequest = http.request(_.extend(options, {
method: 'GET',
path: req.path
}), function (getResponse) {
if (getResponse.statusCode === 200) {
res.setHeader('Content-Type', mimeTypes[path.extname(req.path)]);
res.setHeader('Cache-Control', 'public, max-age=31536000000');
getResponse.pipe(res);
} else {
res.sendStatus(404);
}
});
getRequest.on('error', function () {
res.sendStatus(503);
});
getRequest.end();
};
};
module.exports = HTTPStore;
@andrienpecson
Copy link

Hello how can we implement this to a ghost package. Hope for your response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment