UNPKG

2.57 kBJavaScriptView Raw
1'use strict';
2
3// local modules
4
5const auth = require('./auth');
6const httpUtils = require('./utils/http');
7
8// this module
9
10const TYPES = [ 'answerspaces', 'interactions' ];
11
12function assertIdOption (options) {
13 if (!options.id) {
14 throw new TypeError('"id" must be provided');
15 }
16}
17
18function assertTypeOption (options) {
19 if (!options.type) {
20 throw new TypeError('"type" must be provided');
21 }
22}
23
24function assertKnownTypeOption (options) {
25 if (!~TYPES.indexOf(options.type)) {
26 throw new TypeError(`"${options.type}" is not a known type`);
27 }
28}
29
30function assertDataOption (options) {
31 if (!options.data || typeof options.data !== 'object') {
32 throw new TypeError(`"data" object is mandatory`);
33 }
34}
35
36function assertMatchingIdOption (options) {
37 if (options.id !== options.data.id) {
38 throw new TypeError('"id"s in resource and options do not match');
39 }
40}
41
42function getDashboard () {
43 return auth.read()
44 .then((a) => httpUtils.sendRequest({
45 credential: a.credential,
46 url: `${a.origin}/_api/v1/dashboard`
47 }));
48}
49
50function decorateWithOptionsAssertions (fn, assertions) {
51 return (options) => {
52 options = options || {};
53 assertions.forEach((assert) => assert(options));
54
55 return fn(options);
56 };
57}
58
59const deleteResource = decorateWithOptionsAssertions((options) => {
60 return auth.read()
61 .then((a) => httpUtils.sendRequest({
62 credential: a.credential,
63 method: 'DELETE',
64 url: `${a.origin}/_api/v1/${options.type}/${options.id}`
65 }));
66}, [
67 assertIdOption,
68 assertTypeOption,
69 assertKnownTypeOption
70]);
71
72const getResource = decorateWithOptionsAssertions((options) => {
73 return auth.read()
74 .then((a) => httpUtils.sendRequest({
75 credential: a.credential,
76 url: `${a.origin}/_api/v1/${options.type}/${options.id}`
77 }));
78}, [
79 assertIdOption,
80 assertTypeOption,
81 assertKnownTypeOption
82]);
83
84const putResource = decorateWithOptionsAssertions((options) => {
85 const body = {};
86 body[options.type] = options.data;
87 let method;
88 let urlPath;
89 if (options.id) {
90 method = 'PUT';
91 urlPath = `/_api/v1/${options.type}/${options.id}`;
92 } else {
93 method = 'POST';
94 urlPath = `/_api/v1/${options.type}`;
95 }
96 return auth.read()
97 .then((a) => httpUtils.sendRequest({
98 body,
99 credential: a.credential,
100 method,
101 url: `${a.origin}${urlPath}`
102 }));
103}, [
104 assertTypeOption,
105 assertKnownTypeOption,
106 assertDataOption,
107 assertMatchingIdOption
108]);
109
110module.exports = {
111 deleteResource,
112 getDashboard,
113 getResource,
114 putResource,
115 TYPES
116};