1 | var request = require('request');
|
2 | var _ = require('lodash');
|
3 | var urljoin = require('url-join');
|
4 | var log = require('./log');
|
5 | var debug = require('debug')('4front:cli:api');
|
6 | var manifest = require('../package.json');
|
7 |
|
8 | require('simple-errors');
|
9 |
|
10 | module.exports = function(program, options, callback) {
|
11 | _.defaults(options, {
|
12 | method: 'get',
|
13 | headers: {},
|
14 | authenticate: true,
|
15 | json: true,
|
16 | strictSSL: false
|
17 | });
|
18 |
|
19 | if (!program.profile)
|
20 | return callback(new Error("No profile exists"));
|
21 |
|
22 | options.url = urljoin(program.profile.endpoint, 'api', options.path);
|
23 |
|
24 | _.extend(options.headers, {
|
25 | "User-Agent": '4front-cli@' + manifest.version,
|
26 | "Accept": "application/json"
|
27 | });
|
28 |
|
29 |
|
30 | if (options.authenticate === true) {
|
31 | options.headers['X-Access-Token'] = program.profile.jwt.token;
|
32 | }
|
33 |
|
34 | debug("API request to %s", options.url);
|
35 |
|
36 | var method = options.method.toLowerCase();
|
37 | if (method === 'delete') method = 'del';
|
38 |
|
39 | return request[method](options, function(err, resp, body) {
|
40 | if (err) {
|
41 | debug("error %o", err);
|
42 | return callback(err);
|
43 | }
|
44 |
|
45 | debug("Received API status code of %s", resp.statusCode);
|
46 | switch (resp.statusCode) {
|
47 | case 200:
|
48 | case 201:
|
49 | case 202:
|
50 | case 204:
|
51 | return callback(null, body, resp.statusCode);
|
52 |
|
53 | case 401:
|
54 | return callback(Error.http(401, "Authentication error, try running '4front login'"));
|
55 | case 404:
|
56 | case 500:
|
57 | default:
|
58 | debug("error %s from api call", resp.statusCode);
|
59 | return callback(Error.http(resp.statusCode, "Unexpected error", body));
|
60 | }
|
61 | });
|
62 | };
|