[CCSDK-28] populated the seed code for dgbuilder
[ccsdk/distribution.git] / dgbuilder / red / cli / lib / request.js
1 /**
2  * Copyright 2014 IBM Corp.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  **/
16  
17 var when = require("when");
18 var request = require("request");
19 var config = require("./config");
20
21 module.exports = function(path, options) {
22     var basePath = config.target;
23     return when.promise(function(resolve,reject) {
24         options.headers = options.headers||{};
25         options.headers['Accept'] = 'application/json';
26         if (options.method == 'PUT' || options.method == "POST") {
27             options.headers['content-type'] = 'application/json';
28         }
29         options.url = basePath+path;
30         
31         // Pull out the request function so we can stub it in the tests
32         var requestFunc = request.get;
33         
34         if (options.method == 'PUT') {
35             requestFunc = request.put;
36         } else if (options.method == 'POST') {
37             requestFunc = request.post;
38         } else if (options.method == 'DELETE') {
39             requestFunc = request.del;
40         }
41         requestFunc(options, function(error,response,body) {
42             if (!error && response.statusCode == 200) {
43                 resolve(JSON.parse(body));
44             } else if (error) {
45                 reject(error.toString());
46             } else {
47                 reject(response.statusCode+": "+body)
48             }
49         });
50     });
51 }