|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const url = require('url'); |
| 4 | +const Model = require('hof').model; |
| 5 | +const uuid = require('uuid').v4; |
| 6 | +const config = require('../../../config'); |
| 7 | + |
| 8 | +module.exports = class UploadModel extends Model { |
| 9 | + constructor(...args) { |
| 10 | + super(...args); |
| 11 | + this.set('id', uuid()); |
| 12 | + } |
| 13 | + |
| 14 | + async save() { |
| 15 | + const result = await new Promise((resolve, reject) => { |
| 16 | + const attributes = { |
| 17 | + url: config.upload.hostname |
| 18 | + }; |
| 19 | + const reqConf = url.parse(this.url(attributes)); |
| 20 | + reqConf.formData = { |
| 21 | + document: { |
| 22 | + value: this.get('data'), |
| 23 | + options: { |
| 24 | + filename: this.get('name'), |
| 25 | + contentType: this.get('mimetype') |
| 26 | + } |
| 27 | + } |
| 28 | + }; |
| 29 | + reqConf.method = 'POST'; |
| 30 | + this.request(reqConf, (err, data) => { |
| 31 | + if (err) { |
| 32 | + return reject(err); |
| 33 | + } |
| 34 | + resolve(data); |
| 35 | + }); |
| 36 | + }); |
| 37 | + this.set({ url: result.url }); |
| 38 | + return this.unset('data'); |
| 39 | + } |
| 40 | + |
| 41 | + auth() { |
| 42 | + if (!config.keycloak.token) { |
| 43 | + // eslint-disable-next-line no-console |
| 44 | + console.error('keycloak token url is not defined'); |
| 45 | + return Promise.resolve({ |
| 46 | + bearer: 'abc123' |
| 47 | + }); |
| 48 | + } |
| 49 | + const tokenReq = { |
| 50 | + url: config.keycloak.token, |
| 51 | + form: { |
| 52 | + username: config.keycloak.username, |
| 53 | + password: config.keycloak.password, |
| 54 | + grant_type: 'password', |
| 55 | + client_id: config.keycloak.clientId, |
| 56 | + client_secret: config.keycloak.secret |
| 57 | + }, |
| 58 | + method: 'POST' |
| 59 | + }; |
| 60 | + |
| 61 | + return new Promise((resolve, reject) => { |
| 62 | + this._request(tokenReq, (err, response) => { |
| 63 | + const body = JSON.parse(response.body); |
| 64 | + |
| 65 | + if (err || body.error) { |
| 66 | + return reject(err || new Error(`${body.error} - ${body.error_description}`)); |
| 67 | + } |
| 68 | + |
| 69 | + resolve({ |
| 70 | + bearer: JSON.parse(response.body).access_token |
| 71 | + }); |
| 72 | + }); |
| 73 | + }); |
| 74 | + } |
| 75 | +}; |
0 commit comments