UNPKG

2.61 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 scope = require('./scope');
19const validate = require('./validate');
20const values = require('./values');
21
22// this module
23
24const mkdirpp = pify(mkdirp);
25
26function pruneInteractions (options) {
27 const ids = options.interactions;
28 return resource.listInteractions({ cwd: options.cwd })
29 .then((interactions) => {
30 return interactions.filter((interaction) => !~ids.indexOf(interaction.id));
31 })
32 .then((interactions) => asyncp.eachSeries(interactions, asyncp.asyncify((i) => {
33 return resource.deleteInteraction({ cwd: options.cwd, name: i.name });
34 })));
35}
36
37function pullAnswerSpace (options) {
38 let interactions;
39 return scope.getUID()
40 .then((uid) => api.getResource({ uid, 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 return resource.readCachedAnswerSpace({ cwd: options.cwd })
53 .then((data) => api.getResource({
54 id: '' + options.id, // ensure id is a string
55 type: 'interactions',
56 uid: data.name
57 }))
58 .then((result) => resource.writeInteraction({
59 cwd: options.cwd,
60 data: result.interactions,
61 name: result.interactions.name
62 }));
63}
64
65function pullInteractions (options) {
66 const cwd = options.cwd;
67 const interactions = options.interactions;
68
69 progress.addWork(interactions.length);
70 return mkdirpp(path.join(cwd, 'interactions'))
71 .then(() => asyncp.eachLimit(interactions, values.MAX_REQUESTS, asyncp.asyncify((id) => {
72 return pullInteraction({ cwd, id })
73 .then(() => progress.completeWork(1));
74 })));
75}
76
77function pullAll (options) {
78 options = options || {};
79 const cwd = process.env.BMP_WORKING_DIR || process.cwd();
80
81 return validate.validateScopeMatchesContent({ cwd })
82 .then(() => pullAnswerSpace({ cwd }))
83 .then((interactions) => {
84 if (options.prune) {
85 return pruneInteractions({ cwd, interactions })
86 .then(() => interactions);
87 }
88 return interactions;
89 })
90 .then((interactions) => pullInteractions({ cwd, interactions }));
91}
92
93module.exports = {
94 pullAll
95};