Skip to content

Commit a77b77b

Browse files
author
Perki
committed
Publishing v1.4.5
1 parent 0887073 commit a77b77b

File tree

9 files changed

+166
-46
lines changed

9 files changed

+166
-46
lines changed

CHANGELOG.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@
33
<!-- Format based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -->
44

55

6-
## [Unreleased](https://github.com/pryv/lib-js/compare/2.3.1...HEAD)
6+
## [Unreleased](https://github.com/pryv/lib-js/compare/2.4.5...HEAD)
77

8+
## [2.4.5](https://github.com/pryv/lib-js/compare/2.3.1...2.4.5)
9+
- Enhanced typescripts definition
10+
- Adding `Connextion.apiOne()` and `Connextion.apiOne()`
11+
- Some untracked changes
812

913
## [2.3.1](https://github.com/pryv/lib-js/compare/2.2.0...2.3.1)
1014

components/pryv-monitor/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@pryv/monitor",
3-
"version": "2.4.0",
3+
"version": "2.4.5",
44
"description": "Extends `pryv` with event-driven notifications for changes on a Pryv.io account",
55
"keywords": [
66
"Pryv",

components/pryv-socket.io/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@pryv/socket.io",
3-
"version": "2.4.0",
3+
"version": "2.4.5",
44
"description": "Extends `pryv` with Socket.IO transport",
55
"keywords": [
66
"Pryv",

components/pryv/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "pryv",
3-
"version": "2.4.4",
3+
"version": "2.4.5",
44
"description": "Pryv JavaScript library",
55
"keywords": [
66
"Pryv",
@@ -21,4 +21,4 @@
2121
"dependencies": {
2222
"superagent": "^9.0.0"
2323
}
24-
}
24+
}

components/pryv/src/Connection.js

Lines changed: 128 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,69 @@ class Connection {
8181
function httpHandler (batchCall) {
8282
return this.post('', batchCall);
8383
}
84-
return await this._chunkedBatchCall(arrayOfAPICalls, progress, httpHandler.bind(this));
84+
return await this._chunkedBatchCall(
85+
arrayOfAPICalls,
86+
progress,
87+
httpHandler.bind(this)
88+
);
89+
}
90+
91+
/**
92+
* Make one api Api call
93+
* @param {string} method - methodId
94+
* @param {Object|Array} [params] - the params associated with this methodId
95+
* @param {string} [resultKey] - if given, returns the value or throws an error if not present
96+
* @throws {Error} if .error is present the response
97+
*/
98+
async apiOne (method, params = {}, expectedKey) {
99+
const result = await this.api([{ method, params }]);
100+
if (
101+
result[0] == null ||
102+
result[0].error ||
103+
(expectedKey != null && result[0][expectedKey] == null)
104+
) {
105+
const innerObject = result[0]?.error || result;
106+
const error = new Error(
107+
`Error for api method: "${method}" with params: ${JSON.stringify(
108+
params
109+
)} >> Result: ${JSON.stringify(innerObject)}"`
110+
);
111+
error.innerObject = innerObject;
112+
throw error;
113+
}
114+
if (expectedKey != null) return result[0][expectedKey];
115+
return result[0];
116+
}
117+
118+
/**
119+
* Revoke : Delete the accessId
120+
* - Do not thow error if access is already revoked, just return null;
121+
* @param {boolean} [throwOnFail = true] - if set to false do not throw Error on failure
122+
* @param {Connection} [usingConnection] - specify which connection issues the revoke, might be necessary when selfRovke
123+
*/
124+
async revoke (throwOnFail = true, usingConnection) {
125+
usingConnection = usingConnection || this;
126+
let accessInfo = null;
127+
// get accessId
128+
try {
129+
accessInfo = await this.accessInfo();
130+
} catch (e) {
131+
if (e.response?.body?.error?.id === 'invalid-access-token') {
132+
return null; // Already revoked OK..
133+
}
134+
if (throwOnFail) throw e;
135+
return null;
136+
}
137+
// delete access
138+
try {
139+
const result = usingConnection.apiOne('accesses.delete', {
140+
id: accessInfo.id
141+
});
142+
return result;
143+
} catch (e) {
144+
if (throwOnFail) throw e;
145+
return null;
146+
}
85147
}
86148

87149
/**
@@ -94,32 +156,52 @@ class Connection {
94156

95157
const res = [];
96158
let percent = 0;
97-
for (let cursor = 0; arrayOfAPICalls.length >= cursor; cursor += this.options.chunkSize) {
159+
for (
160+
let cursor = 0;
161+
arrayOfAPICalls.length >= cursor;
162+
cursor += this.options.chunkSize
163+
) {
98164
const thisBatch = [];
99-
const cursorMax = Math.min(cursor + this.options.chunkSize, arrayOfAPICalls.length);
165+
const cursorMax = Math.min(
166+
cursor + this.options.chunkSize,
167+
arrayOfAPICalls.length
168+
);
100169
// copy only method and params into a back call to be exuted
101170
for (let i = cursor; i < cursorMax; i++) {
102-
thisBatch.push({ method: arrayOfAPICalls[i].method, params: arrayOfAPICalls[i].params });
171+
thisBatch.push({
172+
method: arrayOfAPICalls[i].method,
173+
params: arrayOfAPICalls[i].params
174+
});
103175
}
104176
const resRequest = await callHandler(thisBatch);
105177

106178
// result checks
107179
if (!resRequest || !Array.isArray(resRequest.results)) {
108-
throw new Error('API call result is not an Array: ' + JSON.stringify(resRequest));
180+
throw new Error(
181+
'API call result is not an Array: ' + JSON.stringify(resRequest)
182+
);
109183
}
110184
if (resRequest.results.length !== thisBatch.length) {
111-
throw new Error('API call result Array does not match request: ' + JSON.stringify(resRequest));
185+
throw new Error(
186+
'API call result Array does not match request: ' +
187+
JSON.stringify(resRequest)
188+
);
112189
}
113190

114191
// eventually call handleResult
115192
for (let i = 0; i < resRequest.results.length; i++) {
116193
if (arrayOfAPICalls[i + cursor].handleResult) {
117-
await arrayOfAPICalls[i + cursor].handleResult.call(null, resRequest.results[i]);
194+
await arrayOfAPICalls[i + cursor].handleResult.call(
195+
null,
196+
resRequest.results[i]
197+
);
118198
}
119199
}
120200
Array.prototype.push.apply(res, resRequest.results);
121-
percent = Math.round(100 * res.length / arrayOfAPICalls.length);
122-
if (progress) { progress(percent, res); }
201+
percent = Math.round((100 * res.length) / arrayOfAPICalls.length);
202+
if (progress) {
203+
progress(percent, res);
204+
}
123205
}
124206
return res;
125207
}
@@ -146,13 +228,12 @@ class Connection {
146228
* @returns {request.superagent} Promise from superagent's post request
147229
*/
148230
async postRaw (path, data, queryParams) {
149-
return this._post(path)
150-
.query(queryParams)
151-
.send(data);
231+
return this._post(path).query(queryParams).send(data);
152232
}
153233

154234
_post (path) {
155-
return utils.superagent.post(this.endpoint + path)
235+
return utils.superagent
236+
.post(this.endpoint + path)
156237
.set('Authorization', this.token)
157238
.set('accept', 'json');
158239
}
@@ -178,7 +259,8 @@ class Connection {
178259
*/
179260
getRaw (path, queryParams) {
180261
path = path || '';
181-
return utils.superagent.get(this.endpoint + path)
262+
return utils.superagent
263+
.get(this.endpoint + path)
182264
.set('Authorization', this.token)
183265
.set('accept', 'json')
184266
.query(queryParams);
@@ -189,12 +271,11 @@ class Connection {
189271
* https://api.pryv.com/reference/#add-hf-series-data-points
190272
*/
191273
async addPointsToHFEvent (eventId, fields, points) {
192-
const res = await this.post('events/' + eventId + '/series',
193-
{
194-
format: 'flatJSON',
195-
fields: fields,
196-
points: points
197-
});
274+
const res = await this.post('events/' + eventId + '/series', {
275+
format: 'flatJSON',
276+
fields: fields,
277+
points: points
278+
});
198279
if (!res.status === 'ok') {
199280
throw new Error('Failed loading serie: ' + JSON.stringify(res.status));
200281
}
@@ -212,22 +293,31 @@ class Connection {
212293
async getEventsStreamed (queryParams, forEachEvent) {
213294
const myParser = jsonParser(forEachEvent, queryParams.includeDeletions);
214295
let res = null;
215-
if (typeof window === 'undefined') { // node
296+
if (typeof window === 'undefined') {
297+
// node
216298
res = await this.getRaw('events', queryParams)
217299
.buffer(false)
218300
.parse(myParser);
219-
} else if (typeof fetch !== 'undefined' && !(typeof navigator !== 'undefined' && navigator.product === 'ReactNative')) { // browser supports fetch and it is not react native
301+
} else if (
302+
typeof fetch !== 'undefined' &&
303+
!(typeof navigator !== 'undefined' && navigator.product === 'ReactNative')
304+
) {
305+
// browser supports fetch and it is not react native
220306
res = await browserGetEventStreamed(this, queryParams, myParser);
221-
} else { // browser no fetch supports
222-
console.log('WARNING: Browser does not support fetch() required by pryv.Connection.getEventsStreamed()');
307+
} else {
308+
// browser no fetch supports
309+
console.log(
310+
'WARNING: Browser does not support fetch() required by pryv.Connection.getEventsStreamed()'
311+
);
223312
res = await this.getRaw('events', queryParams);
224313
res.body.eventsCount = 0;
225314
if (res.body.events) {
226315
res.body.events.forEach(forEachEvent);
227316
res.body.eventsCount += res.body.events.length;
228317
delete res.body.events;
229318
}
230-
if (res.body.eventDeletions) { // deletions are in a seprated Array
319+
if (res.body.eventDeletions) {
320+
// deletions are in a seprated Array
231321
res.body.eventDeletions.forEach(forEachEvent);
232322
res.body.eventsCount += res.body.eventDeletions.length;
233323
delete res.body.eventDeletions;
@@ -262,7 +352,8 @@ class Connection {
262352
* @param {string} fileName
263353
*/
264354
async createEventWithFileFromBuffer (event, bufferData, filename) {
265-
if (typeof window === 'undefined') { // node
355+
if (typeof window === 'undefined') {
356+
// node
266357
const res = await this._post('events')
267358
.field('event', JSON.stringify(event))
268359
.attach('file', bufferData, filename);
@@ -280,11 +371,11 @@ class Connection {
280371
}
281372

282373
/**
283-
* Create an event with attached formData
284-
* !! BROWSER ONLY
285-
* @param {Event} event
286-
* @param {FormData} formData https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
287-
*/
374+
* Create an event with attached formData
375+
* !! BROWSER ONLY
376+
* @param {Event} event
377+
* @param {FormData} formData https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
378+
*/
288379
async createEventWithFormData (event, formData) {
289380
formData.append('event', JSON.stringify(event));
290381
const res = await this._post('events').send(formData);
@@ -313,10 +404,14 @@ class Connection {
313404
// private method that handle meta data parsing
314405
_handleMeta (res, requestLocalTimestamp) {
315406
if (!res.meta) throw new Error('Cannot find .meta in response.');
316-
if (!res.meta.serverTime) throw new Error('Cannot find .meta.serverTime in response.');
407+
if (!res.meta.serverTime) { throw new Error('Cannot find .meta.serverTime in response.'); }
317408

318409
// update deltaTime and weight it
319-
this._deltaTime.value = (this._deltaTime.value * this._deltaTime.weight + res.meta.serverTime - requestLocalTimestamp) / ++this._deltaTime.weight;
410+
this._deltaTime.value =
411+
(this._deltaTime.value * this._deltaTime.weight +
412+
res.meta.serverTime -
413+
requestLocalTimestamp) /
414+
++this._deltaTime.weight;
320415
}
321416
}
322417

components/pryv/src/index.d.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,15 @@ declare module 'pryv' {
577577
apiCalls: Calls,
578578
progress?: APICallProgressHandler,
579579
): 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]>;
580589
getEventsStreamed(
581590
queryParams: Partial<EventQueryParamsStreamQuery>,
582591
forEachEvent: StreamedEventsHandler,
@@ -600,7 +609,7 @@ declare module 'pryv' {
600609
values: Array<string | number>,
601610
): Promise<any>;
602611
accessInfo(): Promise<AccessInfo>;
603-
612+
revoke(throwOnFail?: boolean, usingConnection?: Connection)
604613
readonly deltaTime: number;
605614
readonly apiEndpoint: string;
606615

components/pryv/test/Connection.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,18 @@ describe('Connection', () => {
8989
});
9090
});
9191

92+
describe('.apiOne()', function () {
93+
this.timeout(15000);
94+
it('.apiOne("events.get")', async () => {
95+
const res = await conn.apiOne('events.get');
96+
expect(res.events).to.exist;
97+
});
98+
it('.apiOne("events.get")', async () => {
99+
const res = await conn.apiOne('events.get', {}, 'events');
100+
expect(Array.isArray(res)).to.equal(true);
101+
});
102+
});
103+
92104
describe('.api()', function () {
93105
this.timeout(15000);
94106
it('.api() events.get', async () => {

package-lock.json

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)