@openfn/language-collections 0.1.0 → 0.2.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
@@ -74,27 +74,31 @@ function API() {
74
74
  throw new Error(COLLECTION_NOT_FOUND);
75
75
  }
76
76
  const col = collections[name];
77
- const results = [];
77
+ const items = [];
78
78
  const regex = new RegExp(key.replace("*", "(.*)"));
79
79
  for (const key2 in col) {
80
80
  if (regex.test(key2)) {
81
- results.push({
81
+ items.push({
82
82
  key: key2,
83
83
  value: col[key2]
84
84
  });
85
85
  }
86
86
  }
87
- return { results };
87
+ return { items };
88
88
  };
89
89
  const byKey = (name, key) => {
90
90
  return collections[name][key];
91
91
  };
92
+ const asJSON = (name, key) => {
93
+ return JSON.parse(collections[name][key]);
94
+ };
92
95
  const remove2 = (name, key) => {
93
96
  if (!(name in collections)) {
94
97
  throw new Error(COLLECTION_NOT_FOUND);
95
98
  }
96
99
  const col = collections[name];
97
100
  delete col[key];
101
+ return [key];
98
102
  };
99
103
  const api = {
100
104
  collections,
@@ -103,12 +107,16 @@ function API() {
103
107
  upsert,
104
108
  fetch,
105
109
  remove: remove2,
106
- byKey
110
+ byKey,
111
+ asJSON
107
112
  };
108
113
  return api;
109
114
  }
110
115
  var parsePath = (path) => {
111
- let [_collections, name, key] = path.split("/");
116
+ if (!path.startsWith("/")) {
117
+ path = `/${path}`;
118
+ }
119
+ let [_, _collections, name, key] = path.split("/");
112
120
  return { name, key };
113
121
  };
114
122
  var assertAuth = (req) => {
@@ -154,13 +162,22 @@ function createServer(url = "https://app.openfn.org") {
154
162
  } catch (e) {
155
163
  return { statusCode: 403 };
156
164
  }
165
+ let upserted = 0;
166
+ const errors = [];
157
167
  try {
158
168
  const { name, key } = parsePath(req.path);
159
169
  const body = JSON.parse(req.body);
160
- for (const { key: key2, value } of body) {
170
+ for (const { key: key2, value } of body.items) {
161
171
  api.upsert(name, key2, value);
172
+ upserted++;
162
173
  }
163
- return { statusCode: 200 };
174
+ return {
175
+ statusCode: 200,
176
+ responseOptions: {
177
+ headers: { "Content-Type": "application/json" }
178
+ },
179
+ data: JSON.stringify({ upserted, errors })
180
+ };
164
181
  } catch (e) {
165
182
  if (e.message === COLLECTION_NOT_FOUND) {
166
183
  return { statusCode: 404 };
@@ -175,8 +192,14 @@ function createServer(url = "https://app.openfn.org") {
175
192
  }
176
193
  try {
177
194
  const { name, key } = parsePath(req.path);
178
- api.remove(name, key);
179
- return { statusCode: 200 };
195
+ const keys = api.remove(name, key);
196
+ return {
197
+ statusCode: 200,
198
+ responseOptions: {
199
+ headers: { "Content-Type": "application/json" }
200
+ },
201
+ data: JSON.stringify({ deleted: keys.length, keys })
202
+ };
180
203
  } catch (e) {
181
204
  if (e.message === COLLECTION_NOT_FOUND) {
182
205
  return { statusCode: 404 };
@@ -214,8 +237,11 @@ var client;
214
237
  var getClient = (state) => {
215
238
  var _a;
216
239
  if (!client) {
217
- const baseUrl = ((_a = state.configuration) == null ? void 0 : _a.collections_endpoint) ?? "https://app.openfn.org";
218
- client = new import_undici2.default.client(baseUrl);
240
+ if (!((_a = state.configuration) == null ? void 0 : _a.collections_endpoint)) {
241
+ throw new Error("ERROR: collections_endpoint not set");
242
+ }
243
+ const url = new URL(state.configuration.collections_endpoint);
244
+ client = new import_undici2.default.Client(url.origin);
219
245
  }
220
246
  return client;
221
247
  };
@@ -224,7 +250,10 @@ var setMockClient = (mockClient) => {
224
250
  };
225
251
  function get(name, query = {}) {
226
252
  return async (state) => {
227
- const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
253
+ let [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
254
+ if (typeof resolvedQuery === "string") {
255
+ resolvedQuery = { key: resolvedQuery };
256
+ }
228
257
  const { key, ...rest } = expandQuery(resolvedQuery);
229
258
  const response = await request(
230
259
  state,
@@ -234,12 +263,18 @@ function get(name, query = {}) {
234
263
  );
235
264
  let data;
236
265
  if (!key.match(/\*/) || Object.keys(resolvedQuery).length === 0) {
237
- [data] = (await response.body.json()).results;
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;
238
272
  console.log(`Fetched "${key}" from collection "${name}"`);
239
273
  } else {
240
274
  data = [];
241
275
  console.log(`Downloading data from collection "${name}"...`);
242
276
  await streamResponse(response, (item) => {
277
+ item.value = JSON.parse(item.value);
243
278
  data.push(item);
244
279
  });
245
280
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
@@ -257,15 +292,31 @@ function set(name, keyGen, values) {
257
292
  );
258
293
  const dataArray = Array.isArray(resolvedValues) ? resolvedValues : [resolvedValues];
259
294
  const keyGenFn = typeof keyGen === "string" ? () => keyGen : keyGen;
260
- const pairs = dataArray.map((value) => ({ key: keyGenFn(value), value }));
261
- console.log(`Setting ${pairs.length} values in collection "${name}"`);
295
+ const pairs = dataArray.map((value, index) => ({
296
+ key: keyGenFn(value, index),
297
+ value: JSON.stringify(value)
298
+ }));
262
299
  const response = await request(state, getClient(state), resolvedName, {
263
300
  method: "POST",
264
- body: JSON.stringify(pairs),
265
- heeaders: {
301
+ body: JSON.stringify({ items: pairs }),
302
+ headers: {
266
303
  "content-type": "application/json"
267
304
  }
268
305
  });
306
+ if (response.statusCode >= 400) {
307
+ console.log(
308
+ `Error setting ${pairs.length} values in collection "${name}"`
309
+ );
310
+ const text = await response.body.text();
311
+ const e = new Error("ERROR from collections server:" + 400);
312
+ e.body = text;
313
+ throw e;
314
+ }
315
+ const result = await response.body.json();
316
+ console.log(`Set ${result.upserted} values in collection "${name}"`);
317
+ if (result.error) {
318
+ console.log(`Errors reported on set:`, result.error);
319
+ }
269
320
  return state;
270
321
  };
271
322
  }
@@ -282,10 +333,13 @@ function remove(name, query = {}, options = {}) {
282
333
  query: rest
283
334
  }
284
335
  );
336
+ const result = await response.body.json();
337
+ console.log(`Set ${result.upserts} values in collection "${name}"`);
285
338
  return state;
286
339
  };
287
340
  }
288
- function each(name, query = {}, callback = {}) {
341
+ function each(name, query = {}, callback = () => {
342
+ }) {
289
343
  return async (state) => {
290
344
  const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
291
345
  const { key, ...rest } = expandQuery(resolvedQuery);
@@ -295,8 +349,8 @@ function each(name, query = {}, callback = {}) {
295
349
  `${resolvedName}/${key}`,
296
350
  { query: rest }
297
351
  );
298
- await streamResponse(response, async ({ key: key2, value }) => {
299
- await callback(state, value, key2);
352
+ await streamResponse(response, async ({ value, key: key2 }) => {
353
+ await callback(state, JSON.parse(value), key2);
300
354
  });
301
355
  return state;
302
356
  };
@@ -305,7 +359,7 @@ var streamResponse = async (response, onValue) => {
305
359
  const pipeline = (0, import_stream_chain.default)([
306
360
  response.body,
307
361
  (0, import_stream_json.default)(),
308
- new import_Pick.default({ filter: "results" }),
362
+ new import_Pick.default({ filter: "items" }),
309
363
  new import_StreamArray.default()
310
364
  ]);
311
365
  for await (const { key, value } of pipeline) {
@@ -343,19 +397,21 @@ var request = (state, client2, path, options = {}) => {
343
397
  path
344
398
  });
345
399
  }
400
+ const basePath = new URL(state.configuration.collections_endpoint).pathname;
346
401
  const headers = {
347
402
  Authorization: `Bearer ${state.configuration.collections_token}`
348
403
  };
349
404
  Object.assign(headers, options == null ? void 0 : options.headers);
350
405
  const { headers: _h, query: _q, ...otherOptions } = options;
351
406
  const query = parseQuery(options.query);
352
- return client2.request({
353
- path: import_node_path.default.join("collections", path),
407
+ const args = {
408
+ path: import_node_path.default.join(basePath, path),
354
409
  headers,
355
410
  method: "GET",
356
411
  query,
357
412
  ...otherOptions
358
- });
413
+ };
414
+ return client2.request(args);
359
415
  };
360
416
  // Annotate the CommonJS export names for ESM import in node:
361
417
  0 && (module.exports = {
package/dist/index.js CHANGED
@@ -49,27 +49,31 @@ function API() {
49
49
  throw new Error(COLLECTION_NOT_FOUND);
50
50
  }
51
51
  const col = collections[name];
52
- const results = [];
52
+ const items = [];
53
53
  const regex = new RegExp(key.replace("*", "(.*)"));
54
54
  for (const key2 in col) {
55
55
  if (regex.test(key2)) {
56
- results.push({
56
+ items.push({
57
57
  key: key2,
58
58
  value: col[key2]
59
59
  });
60
60
  }
61
61
  }
62
- return { results };
62
+ return { items };
63
63
  };
64
64
  const byKey = (name, key) => {
65
65
  return collections[name][key];
66
66
  };
67
+ const asJSON = (name, key) => {
68
+ return JSON.parse(collections[name][key]);
69
+ };
67
70
  const remove2 = (name, key) => {
68
71
  if (!(name in collections)) {
69
72
  throw new Error(COLLECTION_NOT_FOUND);
70
73
  }
71
74
  const col = collections[name];
72
75
  delete col[key];
76
+ return [key];
73
77
  };
74
78
  const api = {
75
79
  collections,
@@ -78,12 +82,16 @@ function API() {
78
82
  upsert,
79
83
  fetch,
80
84
  remove: remove2,
81
- byKey
85
+ byKey,
86
+ asJSON
82
87
  };
83
88
  return api;
84
89
  }
85
90
  var parsePath = (path) => {
86
- let [_collections, name, key] = path.split("/");
91
+ if (!path.startsWith("/")) {
92
+ path = `/${path}`;
93
+ }
94
+ let [_, _collections, name, key] = path.split("/");
87
95
  return { name, key };
88
96
  };
89
97
  var assertAuth = (req) => {
@@ -129,13 +137,22 @@ function createServer(url = "https://app.openfn.org") {
129
137
  } catch (e) {
130
138
  return { statusCode: 403 };
131
139
  }
140
+ let upserted = 0;
141
+ const errors = [];
132
142
  try {
133
143
  const { name, key } = parsePath(req.path);
134
144
  const body = JSON.parse(req.body);
135
- for (const { key: key2, value } of body) {
145
+ for (const { key: key2, value } of body.items) {
136
146
  api.upsert(name, key2, value);
147
+ upserted++;
137
148
  }
138
- return { statusCode: 200 };
149
+ return {
150
+ statusCode: 200,
151
+ responseOptions: {
152
+ headers: { "Content-Type": "application/json" }
153
+ },
154
+ data: JSON.stringify({ upserted, errors })
155
+ };
139
156
  } catch (e) {
140
157
  if (e.message === COLLECTION_NOT_FOUND) {
141
158
  return { statusCode: 404 };
@@ -150,8 +167,14 @@ function createServer(url = "https://app.openfn.org") {
150
167
  }
151
168
  try {
152
169
  const { name, key } = parsePath(req.path);
153
- api.remove(name, key);
154
- return { statusCode: 200 };
170
+ const keys = api.remove(name, key);
171
+ return {
172
+ statusCode: 200,
173
+ responseOptions: {
174
+ headers: { "Content-Type": "application/json" }
175
+ },
176
+ data: JSON.stringify({ deleted: keys.length, keys })
177
+ };
155
178
  } catch (e) {
156
179
  if (e.message === COLLECTION_NOT_FOUND) {
157
180
  return { statusCode: 404 };
@@ -189,8 +212,11 @@ var client;
189
212
  var getClient = (state) => {
190
213
  var _a;
191
214
  if (!client) {
192
- const baseUrl = ((_a = state.configuration) == null ? void 0 : _a.collections_endpoint) ?? "https://app.openfn.org";
193
- client = new undici.client(baseUrl);
215
+ if (!((_a = state.configuration) == null ? void 0 : _a.collections_endpoint)) {
216
+ throw new Error("ERROR: collections_endpoint not set");
217
+ }
218
+ const url = new URL(state.configuration.collections_endpoint);
219
+ client = new undici.Client(url.origin);
194
220
  }
195
221
  return client;
196
222
  };
@@ -199,7 +225,10 @@ var setMockClient = (mockClient) => {
199
225
  };
200
226
  function get(name, query = {}) {
201
227
  return async (state) => {
202
- const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
228
+ let [resolvedName, resolvedQuery] = expandReferences(state, name, query);
229
+ if (typeof resolvedQuery === "string") {
230
+ resolvedQuery = { key: resolvedQuery };
231
+ }
203
232
  const { key, ...rest } = expandQuery(resolvedQuery);
204
233
  const response = await request(
205
234
  state,
@@ -209,12 +238,18 @@ function get(name, query = {}) {
209
238
  );
210
239
  let data;
211
240
  if (!key.match(/\*/) || Object.keys(resolvedQuery).length === 0) {
212
- [data] = (await response.body.json()).results;
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;
213
247
  console.log(`Fetched "${key}" from collection "${name}"`);
214
248
  } else {
215
249
  data = [];
216
250
  console.log(`Downloading data from collection "${name}"...`);
217
251
  await streamResponse(response, (item) => {
252
+ item.value = JSON.parse(item.value);
218
253
  data.push(item);
219
254
  });
220
255
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
@@ -232,15 +267,31 @@ function set(name, keyGen, values) {
232
267
  );
233
268
  const dataArray = Array.isArray(resolvedValues) ? resolvedValues : [resolvedValues];
234
269
  const keyGenFn = typeof keyGen === "string" ? () => keyGen : keyGen;
235
- const pairs = dataArray.map((value) => ({ key: keyGenFn(value), value }));
236
- console.log(`Setting ${pairs.length} values in collection "${name}"`);
270
+ const pairs = dataArray.map((value, index) => ({
271
+ key: keyGenFn(value, index),
272
+ value: JSON.stringify(value)
273
+ }));
237
274
  const response = await request(state, getClient(state), resolvedName, {
238
275
  method: "POST",
239
- body: JSON.stringify(pairs),
240
- heeaders: {
276
+ body: JSON.stringify({ items: pairs }),
277
+ headers: {
241
278
  "content-type": "application/json"
242
279
  }
243
280
  });
281
+ if (response.statusCode >= 400) {
282
+ console.log(
283
+ `Error setting ${pairs.length} values in collection "${name}"`
284
+ );
285
+ const text = await response.body.text();
286
+ const e = new Error("ERROR from collections server:" + 400);
287
+ e.body = text;
288
+ throw e;
289
+ }
290
+ const result = await response.body.json();
291
+ console.log(`Set ${result.upserted} values in collection "${name}"`);
292
+ if (result.error) {
293
+ console.log(`Errors reported on set:`, result.error);
294
+ }
244
295
  return state;
245
296
  };
246
297
  }
@@ -257,10 +308,13 @@ function remove(name, query = {}, options = {}) {
257
308
  query: rest
258
309
  }
259
310
  );
311
+ const result = await response.body.json();
312
+ console.log(`Set ${result.upserts} values in collection "${name}"`);
260
313
  return state;
261
314
  };
262
315
  }
263
- function each(name, query = {}, callback = {}) {
316
+ function each(name, query = {}, callback = () => {
317
+ }) {
264
318
  return async (state) => {
265
319
  const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
266
320
  const { key, ...rest } = expandQuery(resolvedQuery);
@@ -270,8 +324,8 @@ function each(name, query = {}, callback = {}) {
270
324
  `${resolvedName}/${key}`,
271
325
  { query: rest }
272
326
  );
273
- await streamResponse(response, async ({ key: key2, value }) => {
274
- await callback(state, value, key2);
327
+ await streamResponse(response, async ({ value, key: key2 }) => {
328
+ await callback(state, JSON.parse(value), key2);
275
329
  });
276
330
  return state;
277
331
  };
@@ -280,7 +334,7 @@ var streamResponse = async (response, onValue) => {
280
334
  const pipeline = chain([
281
335
  response.body,
282
336
  parser(),
283
- new Pick({ filter: "results" }),
337
+ new Pick({ filter: "items" }),
284
338
  new streamArray()
285
339
  ]);
286
340
  for await (const { key, value } of pipeline) {
@@ -318,19 +372,21 @@ var request = (state, client2, path, options = {}) => {
318
372
  path
319
373
  });
320
374
  }
375
+ const basePath = new URL(state.configuration.collections_endpoint).pathname;
321
376
  const headers = {
322
377
  Authorization: `Bearer ${state.configuration.collections_token}`
323
378
  };
324
379
  Object.assign(headers, options == null ? void 0 : options.headers);
325
380
  const { headers: _h, query: _q, ...otherOptions } = options;
326
381
  const query = parseQuery(options.query);
327
- return client2.request({
328
- path: nodepath.join("collections", path),
382
+ const args = {
383
+ path: nodepath.join(basePath, path),
329
384
  headers,
330
385
  method: "GET",
331
386
  query,
332
387
  ...otherOptions
333
- });
388
+ };
389
+ return client2.request(args);
334
390
  };
335
391
  export {
336
392
  collections_exports as collections
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-collections",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "OpenFn collections adaptor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -23,7 +23,7 @@
23
23
  "stream-chain": "^3.3.2",
24
24
  "stream-json": "^1.8.0",
25
25
  "undici": "^5.22.1",
26
- "@openfn/language-common": "2.1.0"
26
+ "@openfn/language-common": "2.1.1"
27
27
  },
28
28
  "devDependencies": {
29
29
  "assertion-error": "2.0.0",
@@ -39,10 +39,9 @@
39
39
  "types": "types/index.d.ts",
40
40
  "main": "dist/index.cjs",
41
41
  "scripts": {
42
- "tmp": "node test.js",
43
42
  "build": "pnpm clean && build-adaptor collections",
44
- "test": "mocha --experimental-specifier-resolution=node --no-warnings **/*.test.js",
45
- "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings *.test.js",
43
+ "test": "mocha --experimental-specifier-resolution=node --no-warnings --recursive",
44
+ "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings --recursive",
46
45
  "clean": "rimraf dist types docs",
47
46
  "pack": "pnpm pack --pack-destination ../../dist",
48
47
  "lint": "eslint src"
@@ -34,7 +34,7 @@ export function get(name: string, query?: string | QueryOptions): (state: any) =
34
34
  * a string key.
35
35
  * @public
36
36
  * @function
37
- * @param keygen - a function which generates a key for each value. Pass a string to set a static key for a single item.
37
+ * @param keygen - a function which generates a key for each value: (value, index) => key. Pass a string to set a static key for a single item.
38
38
  * @param values - an array of values to set, or a single value.
39
39
  * @example <caption>Set a number of values using each value's id property as a key</caption>
40
40
  * collections.set('my-collection', (item) => item.id, $.data)
package/types/mock.d.ts CHANGED
@@ -4,13 +4,14 @@ export function API(): {
4
4
  reset: () => void;
5
5
  upsert: (name: any, key: any, value: any) => void;
6
6
  fetch: (name: any, key: any, query: any) => {
7
- results: {
7
+ items: {
8
8
  key: string;
9
9
  value: any;
10
10
  }[];
11
11
  };
12
- remove: (name: any, key: any) => void;
12
+ remove: (name: any, key: any) => any[];
13
13
  byKey: (name: any, key: any) => any;
14
+ asJSON: (name: any, key: any) => any;
14
15
  };
15
16
  export function createServer(url?: string): {
16
17
  api: any;