UNPKG

2.26 kBtext/coffeescriptView Raw
1Promise = require('bluebird')
2Http = require('http')
3Request = require('request')
4Url = require('url')
5
6Logger = require('./logger')
7PackageJson = require('./package.json')
8Utils = require('./utils')
9
10
11API_CONFIG =
12 allowUnverified: false
13 key: process.env.FAAS_API_KEY
14 secret: process.env.FAAS_API_SECRET
15 hostname: 'api.faas.io'
16
17debug = Logger('api') # Local logger.
18
19
20exports.config = (config) ->
21 if config
22 apiConf = {}
23 apiConf.key = config.apiKey if config.apiKey
24 apiConf.secret = config.apiSecret if config.apiSecret
25 exports.apiConfig(apiConf)
26
27
28exports.apiConfig = (config) ->
29 Utils.extend(API_CONFIG, config)
30 Utils.shallowCopy(API_CONFIG)
31
32
33###
34# Interface for performing API calls.
35###
36exports.api = (options, callback) ->
37 debug('options', options)
38 callback = debug.wrap(callback)
39
40 urlOpts = options.url
41 # Default the credentials.
42 query = { apiKey: API_CONFIG.key, apiSecret: API_CONFIG.secret }
43 if urlOpts.query
44 Utils.extend(query, urlOpts.query)
45 query.npmVer = PackageJson.version
46 urlOpts.query = query
47 urlOpts.hostname = API_CONFIG.hostname
48 urlOpts.protocol = 'https:'
49
50 # Be clear about configuration errors.
51 cfgErrors = []
52 cfgErrors.push('blank api hostname') unless urlOpts.hostname
53 cfgErrors.push('missing api key') unless urlOpts.query.apiKey
54 cfgErrors.push('missing api secret') unless urlOpts.query.apiSecret
55 if cfgErrors.length > 0
56 debug('ERROR urlOpts', urlOpts)
57 callback('Invalid configuration options: '+cfgErrors.join('; '))
58 return
59
60 reqOpts =
61 uri: Url.format(urlOpts)
62 method: options.method || 'GET'
63 json: options.data || true
64 encoding: 'utf8'
65 strictSSL: if API_CONFIG.allowUnverified then false else true # Disable SSL certificate checking.
66
67 debug('reqOpts', reqOpts)
68
69 Request reqOpts, (err, res, body) ->
70 debug('response', res && res.statusCode, res && res.headers, body)
71 if !err && res && (res.statusCode < 200 || res.statusCode >= 300)
72 err = body && body.error || (res.statusCode+": "+Http.STATUS_CODES[res.statusCode])+': '+JSON.stringify(body)
73 if body && body.data
74 body = body.data
75 callback(err, body)
76
77exports.apiQ = (options) ->
78 Promise.fromCallback (callback) ->
79 exports.api(options, callback)