UNPKG

2.52 kBJavaScriptView Raw
1'use strict';
2
3// Node.js built-ins
4
5const path = require('path');
6
7// foreign modules
8
9const pify = require('pify');
10const mkdirp = require('mkdirp');
11
12// local modules
13
14const api = require('./api');
15const asyncp = require('./utils/asyncp');
16const progress = require('./progress');
17const resource = require('./resource');
18const validate = require('./validate');
19const values = require('./values');
20
21// this module
22
23const mkdirpp = pify(mkdirp);
24
25function pruneInteractions (options) {
26 const ids = options.interactions;
27 return resource.listInteractions({ cwd: options.cwd })
28 .then((interactions) => {
29 return interactions.filter((interaction) => !~ids.indexOf(interaction.id));
30 })
31 .then((interactions) => asyncp.eachSeries(interactions, asyncp.asyncify((i) => {
32 return resource.deleteInteraction({ cwd: options.cwd, name: i.name });
33 })));
34}
35
36function pullAnswerSpace (options) {
37 let interactions;
38 return api.getDashboard()
39 .then((obj) => obj.answerSpace.id)
40 .then((id) => api.getResource({ id, type: 'answerspaces' }))
41 .then((result) => {
42 interactions = result.answerspaces.links.interactions || [];
43 return resource.writeAnswerSpace({
44 cwd: options.cwd,
45 data: result.answerspaces
46 });
47 })
48 .then(() => interactions);
49}
50
51function pullInteraction (options) {
52 // always force "id" to be a string
53 return api.getResource({ id: '' + options.id, type: 'interactions' })
54 .then((result) => resource.writeInteraction({
55 cwd: options.cwd,
56 data: result.interactions,
57 name: result.interactions.name
58 }));
59}
60
61function pullInteractions (options) {
62 const cwd = options.cwd;
63 const interactions = options.interactions;
64
65 progress.addWork(interactions.length);
66 return mkdirpp(path.join(cwd, 'interactions'))
67 .then(() => asyncp.eachLimit(interactions, values.MAX_REQUESTS, asyncp.asyncify((id) => {
68 return pullInteraction({ cwd, id })
69 .then(() => progress.completeWork(1));
70 })));
71}
72
73function pullAll (options) {
74 options = options || {};
75 const cwd = process.env.BMP_WORKING_DIR || process.cwd();
76
77 return validate.validateScopeMatchesContent({ cwd })
78 .then(() => pullAnswerSpace({ cwd }))
79 .then((interactions) => {
80 if (options.prune) {
81 return pruneInteractions({ cwd, interactions })
82 .then(() => interactions);
83 }
84 return interactions;
85 })
86 .then((interactions) => pullInteractions({ cwd, interactions }));
87}
88
89module.exports = {
90 pullAll
91};