@openfn/language-collections 0.2.0 → 0.4.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");
@@ -97,8 +98,15 @@ function API() {
97
98
  throw new Error(COLLECTION_NOT_FOUND);
98
99
  }
99
100
  const col = collections[name];
100
- delete col[key];
101
- return [key];
101
+ const regex = new RegExp(key.replace("*", "(.*)"));
102
+ const removed = [];
103
+ for (const key2 in col) {
104
+ if (regex.test(key2)) {
105
+ delete col[key2];
106
+ removed.push(key2);
107
+ }
108
+ }
109
+ return removed;
102
110
  };
103
111
  const api = {
104
112
  collections,
@@ -116,6 +124,7 @@ var parsePath = (path) => {
116
124
  if (!path.startsWith("/")) {
117
125
  path = `/${path}`;
118
126
  }
127
+ path = path.split("?")[0];
119
128
  let [_, _collections, name, key] = path.split("/");
120
129
  return { name, key };
121
130
  };
@@ -138,12 +147,30 @@ function createServer(url = "https://app.openfn.org") {
138
147
  }
139
148
  try {
140
149
  let { name, key } = parsePath(req.path);
141
- if (!key) {
142
- key = "*";
150
+ let body;
151
+ let statusCode = 200;
152
+ if (key) {
153
+ const result = api.byKey(name, key);
154
+ if (!result) {
155
+ body = {};
156
+ statusCode = 204;
157
+ } else {
158
+ body = {
159
+ key,
160
+ value: result
161
+ };
162
+ }
163
+ } else {
164
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
165
+ key = params.get("key") ?? "*";
166
+ const { items } = api.fetch(name, key);
167
+ body = {
168
+ cursor: ["xxx"],
169
+ items
170
+ };
143
171
  }
144
- const body = api.fetch(name, key);
145
172
  return {
146
- statusCode: 200,
173
+ statusCode,
147
174
  data: JSON.stringify(body),
148
175
  responseOptions: {
149
176
  headers: { "Content-Type": "application/json" }
@@ -191,7 +218,11 @@ function createServer(url = "https://app.openfn.org") {
191
218
  return { statusCode: 403 };
192
219
  }
193
220
  try {
194
- const { name, key } = parsePath(req.path);
221
+ let { name, key } = parsePath(req.path);
222
+ if (!key) {
223
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
224
+ key = params.get("key") ?? "*";
225
+ }
195
226
  const keys = api.remove(name, key);
196
227
  return {
197
228
  statusCode: 200,
@@ -255,29 +286,33 @@ function get(name, query = {}) {
255
286
  resolvedQuery = { key: resolvedQuery };
256
287
  }
257
288
  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}"`);
289
+ let q;
290
+ let path = resolvedName;
291
+ if (key.match(/\*/) || Object.keys(rest).length) {
292
+ q = resolvedQuery;
273
293
  } else {
294
+ path = `${resolvedName}/${key}`;
295
+ }
296
+ const response = await request(state, getClient(state), path, { query: q });
297
+ let data;
298
+ if (q) {
274
299
  data = [];
275
300
  console.log(`Downloading data from collection "${name}"...`);
276
- await streamResponse(response, (item) => {
301
+ const cursor = await streamResponse(response, (item) => {
277
302
  item.value = JSON.parse(item.value);
278
303
  data.push(item);
279
304
  });
305
+ data.cursor = cursor;
280
306
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
307
+ } else {
308
+ const body = await response.body.json();
309
+ if (body.value) {
310
+ data = JSON.parse(body.value);
311
+ console.log(`Fetched "${key}" from collection "${name}"`);
312
+ } else {
313
+ data = {};
314
+ console.warn(`Key "${key}" not found in collection "${name}"`);
315
+ }
281
316
  }
282
317
  state.data = data;
283
318
  return state;
@@ -322,19 +357,24 @@ function set(name, keyGen, values) {
322
357
  }
323
358
  function remove(name, query = {}, options = {}) {
324
359
  return async (state) => {
325
- const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
360
+ let [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
361
+ if (typeof resolvedQuery === "string") {
362
+ resolvedQuery = { key: resolvedQuery };
363
+ }
326
364
  const { key, ...rest } = expandQuery(resolvedQuery);
327
- const response = await request(
328
- state,
329
- getClient(state),
330
- `${resolvedName}/${key}`,
331
- {
332
- method: "DELETE",
333
- query: rest
334
- }
335
- );
365
+ let q;
366
+ let path = resolvedName;
367
+ if (key.match(/\*/) || Object.keys(rest).length) {
368
+ q = resolvedQuery;
369
+ } else {
370
+ path = `${resolvedName}/${key}`;
371
+ }
372
+ const response = await request(state, getClient(state), path, {
373
+ method: "DELETE",
374
+ query: q
375
+ });
336
376
  const result = await response.body.json();
337
- console.log(`Set ${result.upserts} values in collection "${name}"`);
377
+ console.log(`Removed ${result.deleted} values in collection "${name}"`);
338
378
  return state;
339
379
  };
340
380
  }
@@ -342,29 +382,79 @@ function each(name, query = {}, callback = () => {
342
382
  }) {
343
383
  return async (state) => {
344
384
  const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
385
+ let q;
386
+ if (typeof resolvedQuery === "string") {
387
+ q = { key: resolvedQuery };
388
+ } else {
389
+ q = resolvedQuery;
390
+ }
345
391
  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 }) => {
392
+ const response = await request(state, getClient(state), resolvedName, {
393
+ query: q
394
+ });
395
+ const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
353
396
  await callback(state, JSON.parse(value), key2);
354
397
  });
398
+ state.data = {
399
+ cursor
400
+ };
355
401
  return state;
356
402
  };
357
403
  }
358
404
  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);
405
+ const pipeline = (0, import_stream_chain.default)([response.body, (0, import_stream_json.default)()]);
406
+ let isInsideItems = false;
407
+ let cursor;
408
+ const it = pipeline.iterator();
409
+ const waitFor = async (...names) => {
410
+ while (true) {
411
+ const next = await it.next();
412
+ if (next.done) {
413
+ return;
414
+ }
415
+ if (names.includes(next.value.name)) {
416
+ return next;
417
+ }
418
+ }
419
+ };
420
+ for await (const token of it) {
421
+ if (!isInsideItems && token.name === "startKey") {
422
+ const next = await waitFor("keyValue");
423
+ if (next.value.value === "cursor") {
424
+ const strValue = await waitFor("stringChunk", "nullValue");
425
+ if (strValue.name === "nullValue") {
426
+ continue;
427
+ }
428
+ cursor = strValue.value.value;
429
+ }
430
+ if (next.value.value === "items") {
431
+ isInsideItems = true;
432
+ await waitFor("startArray");
433
+ }
434
+ }
435
+ if (isInsideItems && token.name === "startObject") {
436
+ let key;
437
+ let value;
438
+ while (!key || !value) {
439
+ const nextKey = await waitFor("keyValue");
440
+ if (nextKey.value.value === "key") {
441
+ key = await waitFor("stringValue");
442
+ }
443
+ if (nextKey.value.value === "value") {
444
+ value = await waitFor("stringValue");
445
+ }
446
+ }
447
+ await onValue({
448
+ key: key.value.value,
449
+ value: value.value.value
450
+ });
451
+ waitFor("endObject");
452
+ }
453
+ if (isInsideItems && token.name === "endArray") {
454
+ isInsideItems = false;
455
+ }
367
456
  }
457
+ return cursor;
368
458
  };
369
459
  var expandQuery = (query) => {
370
460
  let key;
@@ -403,7 +493,7 @@ var request = (state, client2, path, options = {}) => {
403
493
  };
404
494
  Object.assign(headers, options == null ? void 0 : options.headers);
405
495
  const { headers: _h, query: _q, ...otherOptions } = options;
406
- const query = parseQuery(options.query);
496
+ const query = parseQuery(options);
407
497
  const args = {
408
498
  path: import_node_path.default.join(basePath, path),
409
499
  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";
@@ -72,8 +73,15 @@ function API() {
72
73
  throw new Error(COLLECTION_NOT_FOUND);
73
74
  }
74
75
  const col = collections[name];
75
- delete col[key];
76
- return [key];
76
+ const regex = new RegExp(key.replace("*", "(.*)"));
77
+ const removed = [];
78
+ for (const key2 in col) {
79
+ if (regex.test(key2)) {
80
+ delete col[key2];
81
+ removed.push(key2);
82
+ }
83
+ }
84
+ return removed;
77
85
  };
78
86
  const api = {
79
87
  collections,
@@ -91,6 +99,7 @@ var parsePath = (path) => {
91
99
  if (!path.startsWith("/")) {
92
100
  path = `/${path}`;
93
101
  }
102
+ path = path.split("?")[0];
94
103
  let [_, _collections, name, key] = path.split("/");
95
104
  return { name, key };
96
105
  };
@@ -113,12 +122,30 @@ function createServer(url = "https://app.openfn.org") {
113
122
  }
114
123
  try {
115
124
  let { name, key } = parsePath(req.path);
116
- if (!key) {
117
- key = "*";
125
+ let body;
126
+ let statusCode = 200;
127
+ if (key) {
128
+ const result = api.byKey(name, key);
129
+ if (!result) {
130
+ body = {};
131
+ statusCode = 204;
132
+ } else {
133
+ body = {
134
+ key,
135
+ value: result
136
+ };
137
+ }
138
+ } else {
139
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
140
+ key = params.get("key") ?? "*";
141
+ const { items } = api.fetch(name, key);
142
+ body = {
143
+ cursor: ["xxx"],
144
+ items
145
+ };
118
146
  }
119
- const body = api.fetch(name, key);
120
147
  return {
121
- statusCode: 200,
148
+ statusCode,
122
149
  data: JSON.stringify(body),
123
150
  responseOptions: {
124
151
  headers: { "Content-Type": "application/json" }
@@ -166,7 +193,11 @@ function createServer(url = "https://app.openfn.org") {
166
193
  return { statusCode: 403 };
167
194
  }
168
195
  try {
169
- const { name, key } = parsePath(req.path);
196
+ let { name, key } = parsePath(req.path);
197
+ if (!key) {
198
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
199
+ key = params.get("key") ?? "*";
200
+ }
170
201
  const keys = api.remove(name, key);
171
202
  return {
172
203
  statusCode: 200,
@@ -230,29 +261,33 @@ function get(name, query = {}) {
230
261
  resolvedQuery = { key: resolvedQuery };
231
262
  }
232
263
  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}"`);
264
+ let q;
265
+ let path = resolvedName;
266
+ if (key.match(/\*/) || Object.keys(rest).length) {
267
+ q = resolvedQuery;
248
268
  } else {
269
+ path = `${resolvedName}/${key}`;
270
+ }
271
+ const response = await request(state, getClient(state), path, { query: q });
272
+ let data;
273
+ if (q) {
249
274
  data = [];
250
275
  console.log(`Downloading data from collection "${name}"...`);
251
- await streamResponse(response, (item) => {
276
+ const cursor = await streamResponse(response, (item) => {
252
277
  item.value = JSON.parse(item.value);
253
278
  data.push(item);
254
279
  });
280
+ data.cursor = cursor;
255
281
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
282
+ } else {
283
+ const body = await response.body.json();
284
+ if (body.value) {
285
+ data = JSON.parse(body.value);
286
+ console.log(`Fetched "${key}" from collection "${name}"`);
287
+ } else {
288
+ data = {};
289
+ console.warn(`Key "${key}" not found in collection "${name}"`);
290
+ }
256
291
  }
257
292
  state.data = data;
258
293
  return state;
@@ -297,19 +332,24 @@ function set(name, keyGen, values) {
297
332
  }
298
333
  function remove(name, query = {}, options = {}) {
299
334
  return async (state) => {
300
- const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
335
+ let [resolvedName, resolvedQuery] = expandReferences(state, name, query);
336
+ if (typeof resolvedQuery === "string") {
337
+ resolvedQuery = { key: resolvedQuery };
338
+ }
301
339
  const { key, ...rest } = expandQuery(resolvedQuery);
302
- const response = await request(
303
- state,
304
- getClient(state),
305
- `${resolvedName}/${key}`,
306
- {
307
- method: "DELETE",
308
- query: rest
309
- }
310
- );
340
+ let q;
341
+ let path = resolvedName;
342
+ if (key.match(/\*/) || Object.keys(rest).length) {
343
+ q = resolvedQuery;
344
+ } else {
345
+ path = `${resolvedName}/${key}`;
346
+ }
347
+ const response = await request(state, getClient(state), path, {
348
+ method: "DELETE",
349
+ query: q
350
+ });
311
351
  const result = await response.body.json();
312
- console.log(`Set ${result.upserts} values in collection "${name}"`);
352
+ console.log(`Removed ${result.deleted} values in collection "${name}"`);
313
353
  return state;
314
354
  };
315
355
  }
@@ -317,29 +357,79 @@ function each(name, query = {}, callback = () => {
317
357
  }) {
318
358
  return async (state) => {
319
359
  const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
360
+ let q;
361
+ if (typeof resolvedQuery === "string") {
362
+ q = { key: resolvedQuery };
363
+ } else {
364
+ q = resolvedQuery;
365
+ }
320
366
  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 }) => {
367
+ const response = await request(state, getClient(state), resolvedName, {
368
+ query: q
369
+ });
370
+ const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
328
371
  await callback(state, JSON.parse(value), key2);
329
372
  });
373
+ state.data = {
374
+ cursor
375
+ };
330
376
  return state;
331
377
  };
332
378
  }
333
379
  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);
380
+ const pipeline = chain([response.body, parser()]);
381
+ let isInsideItems = false;
382
+ let cursor;
383
+ const it = pipeline.iterator();
384
+ const waitFor = async (...names) => {
385
+ while (true) {
386
+ const next = await it.next();
387
+ if (next.done) {
388
+ return;
389
+ }
390
+ if (names.includes(next.value.name)) {
391
+ return next;
392
+ }
393
+ }
394
+ };
395
+ for await (const token of it) {
396
+ if (!isInsideItems && token.name === "startKey") {
397
+ const next = await waitFor("keyValue");
398
+ if (next.value.value === "cursor") {
399
+ const strValue = await waitFor("stringChunk", "nullValue");
400
+ if (strValue.name === "nullValue") {
401
+ continue;
402
+ }
403
+ cursor = strValue.value.value;
404
+ }
405
+ if (next.value.value === "items") {
406
+ isInsideItems = true;
407
+ await waitFor("startArray");
408
+ }
409
+ }
410
+ if (isInsideItems && token.name === "startObject") {
411
+ let key;
412
+ let value;
413
+ while (!key || !value) {
414
+ const nextKey = await waitFor("keyValue");
415
+ if (nextKey.value.value === "key") {
416
+ key = await waitFor("stringValue");
417
+ }
418
+ if (nextKey.value.value === "value") {
419
+ value = await waitFor("stringValue");
420
+ }
421
+ }
422
+ await onValue({
423
+ key: key.value.value,
424
+ value: value.value.value
425
+ });
426
+ waitFor("endObject");
427
+ }
428
+ if (isInsideItems && token.name === "endArray") {
429
+ isInsideItems = false;
430
+ }
342
431
  }
432
+ return cursor;
343
433
  };
344
434
  var expandQuery = (query) => {
345
435
  let key;
@@ -378,7 +468,7 @@ var request = (state, client2, path, options = {}) => {
378
468
  };
379
469
  Object.assign(headers, options == null ? void 0 : options.headers);
380
470
  const { headers: _h, query: _q, ...otherOptions } = options;
381
- const query = parseQuery(options.query);
471
+ const query = parseQuery(options);
382
472
  const args = {
383
473
  path: nodepath.join(basePath, path),
384
474
  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.4.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;
package/types/mock.d.ts CHANGED
@@ -9,7 +9,7 @@ export function API(): {
9
9
  value: any;
10
10
  }[];
11
11
  };
12
- remove: (name: any, key: any) => any[];
12
+ remove: (name: any, key: any) => string[];
13
13
  byKey: (name: any, key: any) => any;
14
14
  asJSON: (name: any, key: any) => any;
15
15
  };