UNPKG

1.69 kBJavaScriptView Raw
1const fs = require('mz/fs');
2const { homedir } = require('os');
3const path = require('path');
4const yaml = require('js-yaml');
5
6const userConfDirectory = process.env.BINARIS_CONF_DIR || process.env.HOME || homedir();
7const userConfFile = '.binaris.yml';
8const userConfPath = path.join(userConfDirectory, userConfFile);
9
10const loadUserConf = async function loadUserConf() {
11 const confString = await fs.readFile(userConfPath, 'utf8');
12 const userConf = yaml.safeLoad(confString);
13 return userConf;
14};
15
16const saveUserConf = async function saveUserConf(userConf) {
17 const confString = yaml.dump(userConf);
18 await fs.writeFile(userConfPath, confString, 'utf8');
19};
20
21/**
22 * Updates the API key of the users Binaris conf file.
23 * If no conf file exists when the key update request
24 * is sent, one will be created.
25 *
26 * @param {string} apiKey - apiKey to update conf file with
27 */
28const updateAPIKey = async function updateAPIKey(apiKey) {
29 let currentConf = {};
30 try {
31 currentConf = await loadUserConf();
32 } catch (err) {} // eslint-disable-line no-empty
33 await saveUserConf(Object.assign({}, currentConf, { apiKey }));
34};
35
36const getAPIKey = async function getAPIKey() {
37 const apiKey = process.env.BINARIS_API_KEY;
38 if (apiKey) return apiKey;
39
40 let userConf;
41 try {
42 userConf = await loadUserConf();
43 } catch (err) {
44 throw new Error('Binaris conf file could not be read and BINARIS_API_KEY is undefined, please use "bn login"');
45 }
46
47 if (!Object.prototype.hasOwnProperty.call(userConf, 'apiKey')) {
48 throw new Error(
49`Invalid Binaris conf file (missing API key) ${userConfPath}`);
50 }
51 return userConf.apiKey;
52};
53
54module.exports = {
55 getAPIKey,
56 updateAPIKey,
57};