HTTP Store, Storage layer for Ghost 0.6.0 - passes images to a HTTP endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello how can we implement this to a ghost package. Hope for your response