Austin Morton | c64d5dc | 2019-08-26 18:32:13 -0400 | [diff] [blame] | 1 | const logger = require('../logger').logger, |
| 2 | request = require('request'), |
| 3 | StorageBase = require('./storage').StorageBase, |
| 4 | util = require('util'); |
| 5 | |
| 6 | class StorageRemote extends StorageBase { |
| 7 | constructor(httpRootDir, compilerProps) { |
| 8 | super(httpRootDir, compilerProps); |
| 9 | |
| 10 | this.baseUrl = compilerProps.ceProps('remoteStorageServer'); |
| 11 | |
| 12 | const req = request.defaults({ |
| 13 | baseUrl: this.baseUrl |
| 14 | }); |
| 15 | |
| 16 | this.get = util.promisify(req.get); |
| 17 | this.post = util.promisify(req.post); |
| 18 | } |
| 19 | |
| 20 | async handler(req, res) { |
| 21 | let resp; |
| 22 | try { |
| 23 | resp = await this.post('/shortener', { |
| 24 | json: true, |
| 25 | body: req.body |
| 26 | }); |
| 27 | } catch (err) { |
| 28 | logger.error(err); |
| 29 | res.status(500); |
| 30 | res.end(err.message); |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | const url = resp.body.url; |
| 35 | if (!url) { |
| 36 | res.status(resp.statusCode); |
| 37 | res.end(resp.body); |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | const relativeUrl = url.substring(url.lastIndexOf('/z/') + 1); |
| 42 | const shortlink = `${req.protocol}://${req.get('host')}${this.httpRootDir}${relativeUrl}`; |
| 43 | |
| 44 | res.set('Content-Type', 'application/json'); |
| 45 | res.send(JSON.stringify({url: shortlink})); |
| 46 | } |
| 47 | |
| 48 | async expandId(id) { |
| 49 | const resp = await this.get(`/api/shortlinkinfo/${id}`); |
| 50 | |
| 51 | if (resp.statusCode !== 200) throw new Error(`ID ${id} not present in remote storage`); |
| 52 | |
| 53 | return { |
| 54 | config: resp.body, |
| 55 | specialMetadata: null |
| 56 | }; |
| 57 | } |
| 58 | |
| 59 | incrementViewCount() { |
| 60 | return Promise.resolve(); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | module.exports = StorageRemote; |