@openfn/language-collections 0.2.0 → 0.3.0

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/dist/index.cjs CHANGED
@@ -50,6 +50,7 @@ var import_stream_chain = __toESM(require("stream-chain"), 1);
50
50
  var import_stream_json = __toESM(require("stream-json"), 1);
51
51
  var import_Pick = __toESM(require("stream-json/filters/Pick"), 1);
52
52
  var import_StreamArray = __toESM(require("stream-json/streamers/StreamArray"), 1);
53
+ var import_StreamValues = __toESM(require("stream-json/streamers/StreamValues"), 1);
53
54
 
54
55
  // src/mock.js
55
56
  var import_undici = require("undici");
@@ -116,6 +117,7 @@ var parsePath = (path) => {
116
117
  if (!path.startsWith("/")) {
117
118
  path = `/${path}`;
118
119
  }
120
+ path = path.split("?")[0];
119
121
  let [_, _collections, name, key] = path.split("/");
120
122
  return { name, key };
121
123
  };
@@ -138,12 +140,30 @@ function createServer(url = "https://app.openfn.org") {
138
140
  }
139
141
  try {
140
142
  let { name, key } = parsePath(req.path);
141
- if (!key) {
142
- key = "*";
143
+ let body;
144
+ let statusCode = 200;
145
+ if (key) {
146
+ const result = api.byKey(name, key);
147
+ if (!result) {
148
+ body = {};
149
+ statusCode = 204;
150
+ } else {
151
+ body = {
152
+ key,
153
+ value: result
154
+ };
155
+ }
156
+ } else {
157
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
158
+ key = params.get("key") ?? "*";
159
+ const { items } = api.fetch(name, key);
160
+ body = {
161
+ cursor: ["xxx"],
162
+ items
163
+ };
143
164
  }
144
- const body = api.fetch(name, key);
145
165
  return {
146
- statusCode: 200,
166
+ statusCode,
147
167
  data: JSON.stringify(body),
148
168
  responseOptions: {
149
169
  headers: { "Content-Type": "application/json" }
@@ -255,29 +275,33 @@ function get(name, query = {}) {
255
275
  resolvedQuery = { key: resolvedQuery };
256
276
  }
257
277
  const { key, ...rest } = expandQuery(resolvedQuery);
258
- const response = await request(
259
- state,
260
- getClient(state),
261
- `${resolvedName}/${key}`,
262
- { query: rest }
263
- );
264
- let data;
265
- if (!key.match(/\*/) || Object.keys(resolvedQuery).length === 0) {
266
- const body = await response.body.json();
267
- const item = body.items[0];
268
- if (item) {
269
- item.value = JSON.parse(item.value);
270
- }
271
- data = item;
272
- console.log(`Fetched "${key}" from collection "${name}"`);
278
+ let q;
279
+ let path = resolvedName;
280
+ if (key.match(/\*/) || Object.keys(rest).length) {
281
+ q = resolvedQuery;
273
282
  } else {
283
+ path = `${resolvedName}/${key}`;
284
+ }
285
+ const response = await request(state, getClient(state), path, { query: q });
286
+ let data;
287
+ if (q) {
274
288
  data = [];
275
289
  console.log(`Downloading data from collection "${name}"...`);
276
- await streamResponse(response, (item) => {
290
+ const cursor = await streamResponse(response, (item) => {
277
291
  item.value = JSON.parse(item.value);
278
292
  data.push(item);
279
293
  });
294
+ data.cursor = cursor;
280
295
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
296
+ } else {
297
+ const body = await response.body.json();
298
+ if (body.value) {
299
+ data = JSON.parse(body.value);
300
+ console.log(`Fetched "${key}" from collection "${name}"`);
301
+ } else {
302
+ data = {};
303
+ console.warn(`Key "${key}" not found in collection "${name}"`);
304
+ }
281
305
  }
282
306
  state.data = data;
283
307
  return state;
@@ -342,29 +366,80 @@ function each(name, query = {}, callback = () => {
342
366
  }) {
343
367
  return async (state) => {
344
368
  const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
369
+ let q;
370
+ if (typeof resolvedQuery === "string") {
371
+ q = { key: resolvedQuery };
372
+ } else {
373
+ q = resolvedQuery;
374
+ }
345
375
  const { key, ...rest } = expandQuery(resolvedQuery);
346
- const response = await request(
347
- state,
348
- getClient(state),
349
- `${resolvedName}/${key}`,
350
- { query: rest }
351
- );
352
- await streamResponse(response, async ({ value, key: key2 }) => {
376
+ const response = await request(state, getClient(state), resolvedName, {
377
+ query: q
378
+ });
379
+ console.log(`each response`, response.statusCode);
380
+ const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
353
381
  await callback(state, JSON.parse(value), key2);
354
382
  });
383
+ state.data = {
384
+ cursor
385
+ };
355
386
  return state;
356
387
  };
357
388
  }
358
389
  var streamResponse = async (response, onValue) => {
359
- const pipeline = (0, import_stream_chain.default)([
360
- response.body,
361
- (0, import_stream_json.default)(),
362
- new import_Pick.default({ filter: "items" }),
363
- new import_StreamArray.default()
364
- ]);
365
- for await (const { key, value } of pipeline) {
366
- await onValue(value);
390
+ const pipeline = (0, import_stream_chain.default)([response.body, (0, import_stream_json.default)()]);
391
+ let isInsideItems = false;
392
+ let cursor;
393
+ const it = pipeline.iterator();
394
+ const waitFor = async (...names) => {
395
+ while (true) {
396
+ const next = await it.next();
397
+ if (next.done) {
398
+ return;
399
+ }
400
+ if (names.includes(next.value.name)) {
401
+ return next;
402
+ }
403
+ }
404
+ };
405
+ for await (const token of it) {
406
+ if (!isInsideItems && token.name === "startKey") {
407
+ const next = await waitFor("keyValue");
408
+ if (next.value.value === "cursor") {
409
+ const strValue = await waitFor("stringChunk", "nullValue");
410
+ if (strValue.name === "nullValue") {
411
+ continue;
412
+ }
413
+ cursor = strValue.value.value;
414
+ }
415
+ if (next.value.value === "items") {
416
+ isInsideItems = true;
417
+ await waitFor("startArray");
418
+ }
419
+ }
420
+ if (isInsideItems && token.name === "startObject") {
421
+ let key;
422
+ let value;
423
+ while (!key || !value) {
424
+ const nextKey = await waitFor("keyValue");
425
+ if (nextKey.value.value === "key") {
426
+ key = await waitFor("stringValue");
427
+ }
428
+ if (nextKey.value.value === "value") {
429
+ value = await waitFor("stringValue");
430
+ }
431
+ }
432
+ await onValue({
433
+ key: key.value.value,
434
+ value: value.value.value
435
+ });
436
+ waitFor("endObject");
437
+ }
438
+ if (isInsideItems && token.name === "endArray") {
439
+ isInsideItems = false;
440
+ }
367
441
  }
442
+ return cursor;
368
443
  };
369
444
  var expandQuery = (query) => {
370
445
  let key;
@@ -403,7 +478,7 @@ var request = (state, client2, path, options = {}) => {
403
478
  };
404
479
  Object.assign(headers, options == null ? void 0 : options.headers);
405
480
  const { headers: _h, query: _q, ...otherOptions } = options;
406
- const query = parseQuery(options.query);
481
+ const query = parseQuery(options);
407
482
  const args = {
408
483
  path: import_node_path.default.join(basePath, path),
409
484
  headers,
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ import chain from "stream-chain";
25
25
  import parser from "stream-json";
26
26
  import Pick from "stream-json/filters/Pick";
27
27
  import streamArray from "stream-json/streamers/StreamArray";
28
+ import streamValues from "stream-json/streamers/StreamValues";
28
29
 
29
30
  // src/mock.js
30
31
  import { MockAgent } from "undici";
@@ -91,6 +92,7 @@ var parsePath = (path) => {
91
92
  if (!path.startsWith("/")) {
92
93
  path = `/${path}`;
93
94
  }
95
+ path = path.split("?")[0];
94
96
  let [_, _collections, name, key] = path.split("/");
95
97
  return { name, key };
96
98
  };
@@ -113,12 +115,30 @@ function createServer(url = "https://app.openfn.org") {
113
115
  }
114
116
  try {
115
117
  let { name, key } = parsePath(req.path);
116
- if (!key) {
117
- key = "*";
118
+ let body;
119
+ let statusCode = 200;
120
+ if (key) {
121
+ const result = api.byKey(name, key);
122
+ if (!result) {
123
+ body = {};
124
+ statusCode = 204;
125
+ } else {
126
+ body = {
127
+ key,
128
+ value: result
129
+ };
130
+ }
131
+ } else {
132
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
133
+ key = params.get("key") ?? "*";
134
+ const { items } = api.fetch(name, key);
135
+ body = {
136
+ cursor: ["xxx"],
137
+ items
138
+ };
118
139
  }
119
- const body = api.fetch(name, key);
120
140
  return {
121
- statusCode: 200,
141
+ statusCode,
122
142
  data: JSON.stringify(body),
123
143
  responseOptions: {
124
144
  headers: { "Content-Type": "application/json" }
@@ -230,29 +250,33 @@ function get(name, query = {}) {
230
250
  resolvedQuery = { key: resolvedQuery };
231
251
  }
232
252
  const { key, ...rest } = expandQuery(resolvedQuery);
233
- const response = await request(
234
- state,
235
- getClient(state),
236
- `${resolvedName}/${key}`,
237
- { query: rest }
238
- );
239
- let data;
240
- if (!key.match(/\*/) || Object.keys(resolvedQuery).length === 0) {
241
- const body = await response.body.json();
242
- const item = body.items[0];
243
- if (item) {
244
- item.value = JSON.parse(item.value);
245
- }
246
- data = item;
247
- console.log(`Fetched "${key}" from collection "${name}"`);
253
+ let q;
254
+ let path = resolvedName;
255
+ if (key.match(/\*/) || Object.keys(rest).length) {
256
+ q = resolvedQuery;
248
257
  } else {
258
+ path = `${resolvedName}/${key}`;
259
+ }
260
+ const response = await request(state, getClient(state), path, { query: q });
261
+ let data;
262
+ if (q) {
249
263
  data = [];
250
264
  console.log(`Downloading data from collection "${name}"...`);
251
- await streamResponse(response, (item) => {
265
+ const cursor = await streamResponse(response, (item) => {
252
266
  item.value = JSON.parse(item.value);
253
267
  data.push(item);
254
268
  });
269
+ data.cursor = cursor;
255
270
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
271
+ } else {
272
+ const body = await response.body.json();
273
+ if (body.value) {
274
+ data = JSON.parse(body.value);
275
+ console.log(`Fetched "${key}" from collection "${name}"`);
276
+ } else {
277
+ data = {};
278
+ console.warn(`Key "${key}" not found in collection "${name}"`);
279
+ }
256
280
  }
257
281
  state.data = data;
258
282
  return state;
@@ -317,29 +341,80 @@ function each(name, query = {}, callback = () => {
317
341
  }) {
318
342
  return async (state) => {
319
343
  const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
344
+ let q;
345
+ if (typeof resolvedQuery === "string") {
346
+ q = { key: resolvedQuery };
347
+ } else {
348
+ q = resolvedQuery;
349
+ }
320
350
  const { key, ...rest } = expandQuery(resolvedQuery);
321
- const response = await request(
322
- state,
323
- getClient(state),
324
- `${resolvedName}/${key}`,
325
- { query: rest }
326
- );
327
- await streamResponse(response, async ({ value, key: key2 }) => {
351
+ const response = await request(state, getClient(state), resolvedName, {
352
+ query: q
353
+ });
354
+ console.log(`each response`, response.statusCode);
355
+ const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
328
356
  await callback(state, JSON.parse(value), key2);
329
357
  });
358
+ state.data = {
359
+ cursor
360
+ };
330
361
  return state;
331
362
  };
332
363
  }
333
364
  var streamResponse = async (response, onValue) => {
334
- const pipeline = chain([
335
- response.body,
336
- parser(),
337
- new Pick({ filter: "items" }),
338
- new streamArray()
339
- ]);
340
- for await (const { key, value } of pipeline) {
341
- await onValue(value);
365
+ const pipeline = chain([response.body, parser()]);
366
+ let isInsideItems = false;
367
+ let cursor;
368
+ const it = pipeline.iterator();
369
+ const waitFor = async (...names) => {
370
+ while (true) {
371
+ const next = await it.next();
372
+ if (next.done) {
373
+ return;
374
+ }
375
+ if (names.includes(next.value.name)) {
376
+ return next;
377
+ }
378
+ }
379
+ };
380
+ for await (const token of it) {
381
+ if (!isInsideItems && token.name === "startKey") {
382
+ const next = await waitFor("keyValue");
383
+ if (next.value.value === "cursor") {
384
+ const strValue = await waitFor("stringChunk", "nullValue");
385
+ if (strValue.name === "nullValue") {
386
+ continue;
387
+ }
388
+ cursor = strValue.value.value;
389
+ }
390
+ if (next.value.value === "items") {
391
+ isInsideItems = true;
392
+ await waitFor("startArray");
393
+ }
394
+ }
395
+ if (isInsideItems && token.name === "startObject") {
396
+ let key;
397
+ let value;
398
+ while (!key || !value) {
399
+ const nextKey = await waitFor("keyValue");
400
+ if (nextKey.value.value === "key") {
401
+ key = await waitFor("stringValue");
402
+ }
403
+ if (nextKey.value.value === "value") {
404
+ value = await waitFor("stringValue");
405
+ }
406
+ }
407
+ await onValue({
408
+ key: key.value.value,
409
+ value: value.value.value
410
+ });
411
+ waitFor("endObject");
412
+ }
413
+ if (isInsideItems && token.name === "endArray") {
414
+ isInsideItems = false;
415
+ }
342
416
  }
417
+ return cursor;
343
418
  };
344
419
  var expandQuery = (query) => {
345
420
  let key;
@@ -378,7 +453,7 @@ var request = (state, client2, path, options = {}) => {
378
453
  };
379
454
  Object.assign(headers, options == null ? void 0 : options.headers);
380
455
  const { headers: _h, query: _q, ...otherOptions } = options;
381
- const query = parseQuery(options.query);
456
+ const query = parseQuery(options);
382
457
  const args = {
383
458
  path: nodepath.join(basePath, path),
384
459
  headers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-collections",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "OpenFn collections adaptor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -7,17 +7,20 @@
7
7
  * @property {string} createdAfter - matches values that were created after the end of the provided date
8
8
  * @property {string} updatedBefore - matches values that were updated before the start of the provided date
9
9
  * @property {string} updatedAfter - matches values that were updated after the end of the provided date*
10
+ * @property {number} limit - limit the maximum amount of results. Defaults to 1000.
11
+ * @property {string} cursor - set the cursor position to start searching from a specific index.
10
12
  */
11
13
  /**
12
14
  * Fetch one or more values from a collection.
13
15
  * For large datasets, we recommend using each(), which streams data.
14
16
  * You can pass a specific key as a string to only fetch one item, or pass a query
15
17
  * with a key-pattern or a date filter.
18
+ * If not all matching values are returned, the cursor position is written to state.data
16
19
  * @public
17
20
  * @function
18
21
  * @param {string} name - The name of the collection to fetch from
19
22
  * @param {string|QueryOptions} query - A string key or key pattern (with wildcards '*') to fetch, or a query object
20
- * @state data - the downloaded values as an array unless a specific string was specified
23
+ * @state data - the downloaded values as an array unless a specific key was specified, in which case state.data is the value
21
24
  * @example <caption>Get a specific value from a collection</caption>
22
25
  * collections.get('my-collection', '556e0a62')
23
26
  * @example <caption>Get a range of values from a collection with a key pattern</caption>
@@ -71,6 +74,7 @@ export function remove(name: string, query?: string | QueryOptions, options?: {}
71
74
  * @param {string} name - The name of the collection to remove from
72
75
  * @param {string|QueryOptions} query - A string key or key pattern (with wildcards '*') to remove, or a query object
73
76
  * @param {function} callback - A callback invoked for each item `(state, value, key) => void`
77
+ * @state data.cursor - if values are still left on the server, a cursor string will be written to state.data
74
78
  * @example <caption>Iterate over a range of values with wildcards</caption>
75
79
  * collections.each('my-collection', 'record-2024*-appointment-*', (state, value, key) => {
76
80
  * state.cumulativeCost += value.cost;
@@ -83,7 +87,7 @@ export function remove(name: string, query?: string | QueryOptions, options?: {}
83
87
  export function each(name: string, query?: string | QueryOptions, callback?: Function): (state: any) => Promise<any>;
84
88
  export { createServer as createMockServer };
85
89
  export function setMockClient(mockClient: any): void;
86
- export function streamResponse(response: any, onValue: any): Promise<void>;
90
+ export function streamResponse(response: any, onValue: any): Promise<any>;
87
91
  export function expandQuery(query: any): any;
88
92
  export function parseQuery(options?: {}): {};
89
93
  export function request(state: any, client: any, path: any, options?: {}): any;