|
| 1 | +/* |
| 2 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | + * you may not use this file except in compliance with the License. |
| 4 | + * You may obtain a copy of the License at |
| 5 | + * |
| 6 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | + * |
| 8 | + * Unless required by applicable law or agreed to in writing, software |
| 9 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | + * See the License for the specific language governing permissions and |
| 12 | + * limitations under the License. |
| 13 | + */ |
| 14 | + |
| 15 | +'use strict'; |
| 16 | + |
| 17 | +const HTTPService = require('composer-runtime').HTTPService; |
| 18 | +const Logger = require('composer-common').Logger; |
| 19 | +const request = require('request'); |
| 20 | +const LOG = Logger.getLog('EmbeddedHTTPService'); |
| 21 | + |
| 22 | +/** |
| 23 | + * Base class representing the http service provided by a {@link Container}. |
| 24 | + * @protected |
| 25 | + */ |
| 26 | +class EmbeddedHTTPService extends HTTPService { |
| 27 | + |
| 28 | + /** |
| 29 | + * Constructor. |
| 30 | + * @param {EventEmitter} eventSink the event emitter |
| 31 | + */ |
| 32 | + constructor() { |
| 33 | + super(); |
| 34 | + const method = 'constructor'; |
| 35 | + LOG.exit(method); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Post data |
| 40 | + * @abstract |
| 41 | + * @return {Promise} A Promise that return the JSON text for the HTTP POST. It captures the status code, header and body of the HTTP POST. The body must also be returned as embedded JSON text. |
| 42 | + * @throws {Error} throws an error if there is an issue |
| 43 | + */ |
| 44 | + _post() { |
| 45 | + const self = this; |
| 46 | + return new Promise(function (resolve, reject) { |
| 47 | + |
| 48 | + const options = { |
| 49 | + url : self.url, |
| 50 | + method: 'POST', |
| 51 | + body: self.data, |
| 52 | + json: true |
| 53 | + }; |
| 54 | + |
| 55 | + request.post(options, |
| 56 | + function (err, resp, body) { |
| 57 | + LOG.info('error:', err); |
| 58 | + LOG.info('statusCode:', resp && resp.statusCode); |
| 59 | + LOG.info('body:', body); |
| 60 | + |
| 61 | + if(resp) { |
| 62 | + resolve( JSON.stringify({ |
| 63 | + statusCode: resp.statusCode, |
| 64 | + body: (err) ? err : body |
| 65 | + })); |
| 66 | + } |
| 67 | + else { |
| 68 | + reject( JSON.stringify({ |
| 69 | + statusCode: 500, |
| 70 | + body: (err) ? err : body |
| 71 | + })); |
| 72 | + } |
| 73 | + }); |
| 74 | + }); |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +module.exports = EmbeddedHTTPService; |
0 commit comments