pryv 2.4.5 → 2.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -199,7 +199,7 @@ try {
199
199
  ```js
200
200
  let count = 0;
201
201
  // the following will be called on each API method result it was provided for
202
- function handleResult(result) { console.log('Got result ' + count++ + ': ' + JSON.stringify(result)); }
202
+ function handleResult(result, apiCall) { console.log('Got result ' + count++ + ': ' + JSON.stringify(result) + ' For call ' + JSON.stringify(apiCall)); }
203
203
 
204
204
  function progress(percentage) { console.log('Processed: ' + percentage + '%'); }
205
205
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pryv",
3
- "version": "2.4.5",
3
+ "version": "2.4.7",
4
4
  "description": "Pryv JavaScript library",
5
5
  "keywords": [
6
6
  "Pryv",
@@ -12,7 +12,7 @@
12
12
  },
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "git://github.com/pryv/lib-js"
15
+ "url": "git://github.com/pryv/lib-js.git"
16
16
  },
17
17
  "license": "BSD-3-Clause",
18
18
  "author": "Pryv S.A. <info@pryv.com> (https://pryv.com)",
package/src/Connection.js CHANGED
@@ -26,7 +26,7 @@ const browserGetEventStreamed = require('./lib/browser-getEventStreamed');
26
26
  * @param {pryv.Service} [service] - eventually initialize Connection with a Service
27
27
  */
28
28
  class Connection {
29
- constructor(apiEndpoint, service) {
29
+ constructor (apiEndpoint, service) {
30
30
  const { token, endpoint } = utils.extractTokenAndAPIEndpoint(apiEndpoint);
31
31
  this.token = token;
32
32
  this.endpoint = endpoint;
@@ -34,7 +34,7 @@ class Connection {
34
34
  this.options.chunkSize = 1000;
35
35
  this._deltaTime = { value: 0, weight: 0 };
36
36
  if (service && !(service instanceof Service)) {
37
- throw new Error("Invalid service param");
37
+ throw new Error('Invalid service param');
38
38
  }
39
39
  this._service = service;
40
40
  }
@@ -44,9 +44,9 @@ class Connection {
44
44
  * @readonly
45
45
  * @property {pryv.Service} service
46
46
  */
47
- get service() {
47
+ get service () {
48
48
  if (this._service) return this._service;
49
- this._service = new Service(this.endpoint + "service/info");
49
+ this._service = new Service(this.endpoint + 'service/info');
50
50
  return this._service;
51
51
  }
52
52
 
@@ -56,7 +56,7 @@ class Connection {
56
56
  * @param {*} arrayOfAPICalls
57
57
  * @param {*} progress
58
58
  */
59
- async username() {
59
+ async username () {
60
60
  const accessInfo = await this.accessInfo();
61
61
  return accessInfo.user.username;
62
62
  }
@@ -65,8 +65,8 @@ class Connection {
65
65
  * get access info
66
66
  * It's async as it is constructed with get function.
67
67
  */
68
- async accessInfo() {
69
- return this.get("access-info", null);
68
+ async accessInfo () {
69
+ return this.get('access-info', null);
70
70
  }
71
71
 
72
72
  /**
@@ -77,9 +77,9 @@ class Connection {
77
77
  * @param {Function} [progress] Return percentage of progress (0 - 100);
78
78
  * @returns {Promise<Array>} Promise to Array of results matching each method call in order
79
79
  */
80
- async api(arrayOfAPICalls, progress) {
81
- function httpHandler(batchCall) {
82
- return this.post("", batchCall);
80
+ async api (arrayOfAPICalls, progress) {
81
+ function httpHandler (batchCall) {
82
+ return this.post('', batchCall);
83
83
  }
84
84
  return await this._chunkedBatchCall(
85
85
  arrayOfAPICalls,
@@ -95,7 +95,7 @@ class Connection {
95
95
  * @param {string} [resultKey] - if given, returns the value or throws an error if not present
96
96
  * @throws {Error} if .error is present the response
97
97
  */
98
- async apiOne(method, params = {}, expectedKey) {
98
+ async apiOne (method, params = {}, expectedKey) {
99
99
  const result = await this.api([{ method, params }]);
100
100
  if (
101
101
  result[0] == null ||
@@ -121,14 +121,14 @@ class Connection {
121
121
  * @param {boolean} [throwOnFail = true] - if set to false do not throw Error on failure
122
122
  * @param {Connection} [usingConnection] - specify which connection issues the revoke, might be necessary when selfRovke
123
123
  */
124
- async revoke(throwOnFail = true, usingConnection) {
124
+ async revoke (throwOnFail = true, usingConnection) {
125
125
  usingConnection = usingConnection || this;
126
126
  let accessInfo = null;
127
127
  // get accessId
128
128
  try {
129
129
  accessInfo = await this.accessInfo();
130
130
  } catch (e) {
131
- if (e.response?.body?.error?.id === "invalid-access-token") {
131
+ if (e.response?.body?.error?.id === 'invalid-access-token') {
132
132
  return null; // Already revoked OK..
133
133
  }
134
134
  if (throwOnFail) throw e;
@@ -136,8 +136,8 @@ class Connection {
136
136
  }
137
137
  // delete access
138
138
  try {
139
- const result = usingConnection.apiOne("accesses.delete", {
140
- id: accessInfo.id,
139
+ const result = usingConnection.apiOne('accesses.delete', {
140
+ id: accessInfo.id
141
141
  });
142
142
  return result;
143
143
  } catch (e) {
@@ -149,9 +149,9 @@ class Connection {
149
149
  /**
150
150
  * @private
151
151
  */
152
- async _chunkedBatchCall(arrayOfAPICalls, progress, callHandler) {
152
+ async _chunkedBatchCall (arrayOfAPICalls, progress, callHandler) {
153
153
  if (!Array.isArray(arrayOfAPICalls)) {
154
- throw new Error("Connection.api() takes an array as input");
154
+ throw new Error('Connection.api() takes an array as input');
155
155
  }
156
156
 
157
157
  const res = [];
@@ -170,7 +170,7 @@ class Connection {
170
170
  for (let i = cursor; i < cursorMax; i++) {
171
171
  thisBatch.push({
172
172
  method: arrayOfAPICalls[i].method,
173
- params: arrayOfAPICalls[i].params,
173
+ params: arrayOfAPICalls[i].params
174
174
  });
175
175
  }
176
176
  const resRequest = await callHandler(thisBatch);
@@ -178,12 +178,12 @@ class Connection {
178
178
  // result checks
179
179
  if (!resRequest || !Array.isArray(resRequest.results)) {
180
180
  throw new Error(
181
- "API call result is not an Array: " + JSON.stringify(resRequest)
181
+ 'API call result is not an Array: ' + JSON.stringify(resRequest)
182
182
  );
183
183
  }
184
184
  if (resRequest.results.length !== thisBatch.length) {
185
185
  throw new Error(
186
- "API call result Array does not match request: " +
186
+ 'API call result Array does not match request: ' +
187
187
  JSON.stringify(resRequest)
188
188
  );
189
189
  }
@@ -193,7 +193,8 @@ class Connection {
193
193
  if (arrayOfAPICalls[i + cursor].handleResult) {
194
194
  await arrayOfAPICalls[i + cursor].handleResult.call(
195
195
  null,
196
- resRequest.results[i]
196
+ resRequest.results[i],
197
+ thisBatch[i] // request
197
198
  );
198
199
  }
199
200
  }
@@ -213,7 +214,7 @@ class Connection {
213
214
  * @param {string} path
214
215
  * @returns {Promise<Array|Object>} Promise to result.body
215
216
  */
216
- async post(path, data, queryParams) {
217
+ async post (path, data, queryParams) {
217
218
  const now = getTimestamp();
218
219
  const res = await this.postRaw(path, data, queryParams);
219
220
  this._handleMeta(res.body, now);
@@ -227,15 +228,15 @@ class Connection {
227
228
  * @param {string} path
228
229
  * @returns {request.superagent} Promise from superagent's post request
229
230
  */
230
- async postRaw(path, data, queryParams) {
231
+ async postRaw (path, data, queryParams) {
231
232
  return this._post(path).query(queryParams).send(data);
232
233
  }
233
234
 
234
- _post(path) {
235
+ _post (path) {
235
236
  return utils.superagent
236
237
  .post(this.endpoint + path)
237
- .set("Authorization", this.token)
238
- .set("accept", "json");
238
+ .set('Authorization', this.token)
239
+ .set('accept', 'json');
239
240
  }
240
241
 
241
242
  /**
@@ -244,7 +245,7 @@ class Connection {
244
245
  * @param {string} path
245
246
  * @returns {Promise<Array|Object>} Promise to result.body
246
247
  */
247
- async get(path, queryParams) {
248
+ async get (path, queryParams) {
248
249
  const now = getTimestamp();
249
250
  const res = await this.getRaw(path, queryParams);
250
251
  this._handleMeta(res.body, now);
@@ -257,12 +258,12 @@ class Connection {
257
258
  * @param {string} path
258
259
  * @returns {request.superagent} Promise from superagent's get request
259
260
  */
260
- getRaw(path, queryParams) {
261
- path = path || "";
261
+ getRaw (path, queryParams) {
262
+ path = path || '';
262
263
  return utils.superagent
263
264
  .get(this.endpoint + path)
264
- .set("Authorization", this.token)
265
- .set("accept", "json")
265
+ .set('Authorization', this.token)
266
+ .set('accept', 'json')
266
267
  .query(queryParams);
267
268
  }
268
269
 
@@ -270,14 +271,14 @@ class Connection {
270
271
  * ADD Data Points to HFEvent (flatJSON format)
271
272
  * https://api.pryv.com/reference/#add-hf-series-data-points
272
273
  */
273
- async addPointsToHFEvent(eventId, fields, points) {
274
- const res = await this.post("events/" + eventId + "/series", {
275
- format: "flatJSON",
274
+ async addPointsToHFEvent (eventId, fields, points) {
275
+ const res = await this.post('events/' + eventId + '/series', {
276
+ format: 'flatJSON',
276
277
  fields: fields,
277
- points: points,
278
+ points: points
278
279
  });
279
- if (!res.status === "ok") {
280
- throw new Error("Failed loading serie: " + JSON.stringify(res.status));
280
+ if (!res.status === 'ok') {
281
+ throw new Error('Failed loading serie: ' + JSON.stringify(res.status));
281
282
  }
282
283
  return res;
283
284
  }
@@ -290,26 +291,26 @@ class Connection {
290
291
  * @param {Function} forEachEvent Function taking one event as parameter. Will be called for each event
291
292
  * @returns {Promise<Object>} Promise to result.body transformed with `eventsCount: {count}` replacing `events: [...]`
292
293
  */
293
- async getEventsStreamed(queryParams, forEachEvent) {
294
+ async getEventsStreamed (queryParams, forEachEvent) {
294
295
  const myParser = jsonParser(forEachEvent, queryParams.includeDeletions);
295
296
  let res = null;
296
- if (typeof window === "undefined") {
297
+ if (typeof window === 'undefined') {
297
298
  // node
298
- res = await this.getRaw("events", queryParams)
299
+ res = await this.getRaw('events', queryParams)
299
300
  .buffer(false)
300
301
  .parse(myParser);
301
302
  } else if (
302
- typeof fetch !== "undefined" &&
303
- !(typeof navigator !== "undefined" && navigator.product === "ReactNative")
303
+ typeof fetch !== 'undefined' &&
304
+ !(typeof navigator !== 'undefined' && navigator.product === 'ReactNative')
304
305
  ) {
305
306
  // browser supports fetch and it is not react native
306
307
  res = await browserGetEventStreamed(this, queryParams, myParser);
307
308
  } else {
308
309
  // browser no fetch supports
309
310
  console.log(
310
- "WARNING: Browser does not support fetch() required by pryv.Connection.getEventsStreamed()"
311
+ 'WARNING: Browser does not support fetch() required by pryv.Connection.getEventsStreamed()'
311
312
  );
312
- res = await this.getRaw("events", queryParams);
313
+ res = await this.getRaw('events', queryParams);
313
314
  res.body.eventsCount = 0;
314
315
  if (res.body.events) {
315
316
  res.body.events.forEach(forEachEvent);
@@ -335,10 +336,10 @@ class Connection {
335
336
  * @param {Event} event
336
337
  * @param {string} filePath
337
338
  */
338
- async createEventWithFile(event, filePath) {
339
- const res = await this._post("events")
340
- .field("event", JSON.stringify(event))
341
- .attach("file", filePath);
339
+ async createEventWithFile (event, filePath) {
340
+ const res = await this._post('events')
341
+ .field('event', JSON.stringify(event))
342
+ .attach('file', filePath);
342
343
 
343
344
  const now = getTimestamp();
344
345
  this._handleMeta(res.body, now);
@@ -351,12 +352,12 @@ class Connection {
351
352
  * @param {Buffer|Blob} bufferData - Buffer for node, Blob for browser
352
353
  * @param {string} fileName
353
354
  */
354
- async createEventWithFileFromBuffer(event, bufferData, filename) {
355
- if (typeof window === "undefined") {
355
+ async createEventWithFileFromBuffer (event, bufferData, filename) {
356
+ if (typeof window === 'undefined') {
356
357
  // node
357
- const res = await this._post("events")
358
- .field("event", JSON.stringify(event))
359
- .attach("file", bufferData, filename);
358
+ const res = await this._post('events')
359
+ .field('event', JSON.stringify(event))
360
+ .attach('file', bufferData, filename);
360
361
 
361
362
  const now = getTimestamp();
362
363
  this._handleMeta(res.body, now);
@@ -364,7 +365,7 @@ class Connection {
364
365
  } else {
365
366
  /* global FormData */
366
367
  const formData = new FormData();
367
- formData.append("file", bufferData, filename);
368
+ formData.append('file', bufferData, filename);
368
369
  const body = await this.createEventWithFormData(event, formData);
369
370
  return body;
370
371
  }
@@ -376,9 +377,9 @@ class Connection {
376
377
  * @param {Event} event
377
378
  * @param {FormData} formData https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
378
379
  */
379
- async createEventWithFormData(event, formData) {
380
- formData.append("event", JSON.stringify(event));
381
- const res = await this._post("events").send(formData);
380
+ async createEventWithFormData (event, formData) {
381
+ formData.append('event', JSON.stringify(event));
382
+ const res = await this._post('events').send(formData);
382
383
  return res.body;
383
384
  }
384
385
 
@@ -388,7 +389,7 @@ class Connection {
388
389
  * @readonly
389
390
  * @property {number} deltaTime
390
391
  */
391
- get deltaTime() {
392
+ get deltaTime () {
392
393
  return this._deltaTime.value;
393
394
  }
394
395
 
@@ -397,15 +398,14 @@ class Connection {
397
398
  * @readonly
398
399
  * @property {APIEndpoint} deltaTime
399
400
  */
400
- get apiEndpoint() {
401
+ get apiEndpoint () {
401
402
  return utils.buildAPIEndpoint(this);
402
403
  }
403
404
 
404
405
  // private method that handle meta data parsing
405
- _handleMeta(res, requestLocalTimestamp) {
406
- if (!res.meta) throw new Error("Cannot find .meta in response.");
407
- if (!res.meta.serverTime)
408
- throw new Error("Cannot find .meta.serverTime in response.");
406
+ _handleMeta (res, requestLocalTimestamp) {
407
+ if (!res.meta) throw new Error('Cannot find .meta in response.');
408
+ if (!res.meta.serverTime) { throw new Error('Cannot find .meta.serverTime in response.'); }
409
409
 
410
410
  // update deltaTime and weight it
411
411
  this._deltaTime.value =
package/src/index.d.ts CHANGED
@@ -17,7 +17,7 @@ declare module 'pryv' {
17
17
  name: string;
18
18
  parentId?: Identifier;
19
19
  clientData?: KeyValue;
20
- children: Identifier[];
20
+ children: Stream[];
21
21
  trashed?: boolean;
22
22
  created: Timestamp;
23
23
  createdBy: Identifier;
@@ -530,7 +530,7 @@ declare module 'pryv' {
530
530
  APICallMethods[K]['res'] & PossibleError;
531
531
 
532
532
  export type APICallResultHandler<K extends keyof APICallMethods> = (
533
- result: APICallResult<K>,
533
+ result: APICallResult<K>, apicall: APICall<K>
534
534
  ) => Promise<any>;
535
535
  export type StreamedEventsHandler = (event: Event) => void;
536
536
 
@@ -577,15 +577,15 @@ declare module 'pryv' {
577
577
  apiCalls: Calls,
578
578
  progress?: APICallProgressHandler,
579
579
  ): Promise<Array<TypedAPICallResult>>;
580
- apiOne(
581
- method: keyof APICallMethods,
582
- params: APICallMethods[keyof APICallMethods],
583
- ): Promise<TypedAPICallResult>;
584
- apiOne(
585
- method: keyof APICallMethods,
586
- params: APICallMethods[keyof APICallMethods],
587
- expectedKey: string
588
- ): Promise<TypedAPICallResult[keyof TypedAPICallResult]>;
580
+ apiOne<T extends keyof APICallMethods>(
581
+ method: T,
582
+ params: APICallMethods[T]['params'],
583
+ ): Promise<APICallMethods[T]['res']>;
584
+ apiOne<T extends keyof APICallMethods, U extends keyof APICallMethods[T]['res']>(
585
+ method: T,
586
+ params: APICallMethods[T]['params'],
587
+ expectedKey: U
588
+ ): Promise<APICallMethods[T]['res'][U]>;
589
589
  getEventsStreamed(
590
590
  queryParams: Partial<EventQueryParamsStreamQuery>,
591
591
  forEachEvent: StreamedEventsHandler,
@@ -95,7 +95,7 @@ describe('Connection', () => {
95
95
  const res = await conn.apiOne('events.get');
96
96
  expect(res.events).to.exist;
97
97
  });
98
- it('.apiOne("events.get")', async () => {
98
+ it('.apiOne("events.get")', async () => {
99
99
  const res = await conn.apiOne('events.get', {}, 'events');
100
100
  expect(Array.isArray(res)).to.equal(true);
101
101
  });
@@ -129,8 +129,9 @@ describe('Connection', () => {
129
129
  conn.options.chunkSize = 2;
130
130
 
131
131
  let resultsReceivedCount = 0;
132
- function oneMoreResult (res) {
132
+ function oneMoreResult (res, apiCall) {
133
133
  expect(res.events).to.exist;
134
+ expect(apiCall.method).to.equal('events.get');
134
135
  resultsReceivedCount++;
135
136
  }
136
137