@openfn/language-dhis2 6.3.4 → 7.0.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.js CHANGED
@@ -10,13 +10,51 @@ import { createEntity } from "@openfn/language-common/metadata";
10
10
  // src/meta/helper.js
11
11
  import axios from "axios";
12
12
 
13
- // src/Utils.js
13
+ // src/util.js
14
+ var util_exports = {};
15
+ __export(util_exports, {
16
+ CONTENT_TYPES: () => CONTENT_TYPES,
17
+ attr: () => attr,
18
+ configureAuth: () => configureAuth,
19
+ dv: () => dv,
20
+ ensureArray: () => ensureArray,
21
+ findAttributeValue: () => findAttributeValue,
22
+ findAttributeValueById: () => findAttributeValueById,
23
+ handleHttpResponse: () => handleHttpResponse,
24
+ handleResponse: () => handleResponse,
25
+ prefixVersionToPath: () => prefixVersionToPath,
26
+ prettyJson: () => prettyJson,
27
+ request: () => request,
28
+ selectId: () => selectId,
29
+ shouldUseNewTracker: () => shouldUseNewTracker
30
+ });
14
31
  import { composeNextState } from "@openfn/language-common";
32
+ import {
33
+ request as commonRequest,
34
+ makeBasicAuthHeader,
35
+ logResponse
36
+ } from "@openfn/language-common/util";
15
37
  function shouldUseNewTracker(resourceType) {
16
38
  return /^(enrollments|relationships|events|trackedEntities)$/.test(
17
39
  resourceType
18
40
  );
19
41
  }
42
+ function attr(attribute, value) {
43
+ return { attribute, value };
44
+ }
45
+ function dv(dataElement, value) {
46
+ return { dataElement, value };
47
+ }
48
+ function findAttributeValue(trackedEntity, attributeDisplayName) {
49
+ var _a, _b;
50
+ return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find(
51
+ (a) => (a == null ? void 0 : a.displayName.toLowerCase()) == attributeDisplayName.toLowerCase()
52
+ )) == null ? void 0 : _b.value;
53
+ }
54
+ function findAttributeValueById(trackedEntity, attributeUid) {
55
+ var _a, _b;
56
+ return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find((a) => (a == null ? void 0 : a.attribute) == attributeUid)) == null ? void 0 : _b.value;
57
+ }
20
58
  var CONTENT_TYPES = {
21
59
  xml: "application/xml",
22
60
  json: "application/json",
@@ -24,10 +62,6 @@ var CONTENT_TYPES = {
24
62
  csv: "application/csv",
25
63
  xls: "application/vnd.ms-excel"
26
64
  };
27
- function buildUrl(urlString, hostUrl, apiVersion) {
28
- const pathSuffix = apiVersion ? `/${apiVersion}${urlString}` : `${urlString}`;
29
- return hostUrl + "/api" + pathSuffix;
30
- }
31
65
  function selectId(resourceType) {
32
66
  switch (resourceType) {
33
67
  case "trackedEntityInstances":
@@ -36,11 +70,20 @@ function selectId(resourceType) {
36
70
  return "id";
37
71
  }
38
72
  }
39
- function handleResponse(result, state, callback) {
40
- const { data } = result;
41
- if (callback)
42
- return callback(composeNextState(state, data));
43
- return composeNextState(state, data);
73
+ function handleHttpResponse(result, state) {
74
+ const { body, ...responseWithoutBody } = result;
75
+ const nextState = {
76
+ ...composeNextState(state, body),
77
+ response: responseWithoutBody
78
+ };
79
+ return nextState;
80
+ }
81
+ function handleResponse(result, state) {
82
+ const { body } = result;
83
+ const nextState = {
84
+ ...composeNextState(state, body)
85
+ };
86
+ return nextState;
44
87
  }
45
88
  function prettyJson(data) {
46
89
  return JSON.stringify(data, null, 2);
@@ -48,23 +91,61 @@ function prettyJson(data) {
48
91
  function ensureArray(data, key) {
49
92
  return Array.isArray(data) ? { [key]: data } : { [key]: [data] };
50
93
  }
51
- function generateUrl(configuration, options, resourceType, path = null) {
52
- let { hostUrl, apiVersion } = configuration;
94
+ function prefixVersionToPath(configuration, options, resourceType, path = null) {
95
+ let { apiVersion } = configuration;
53
96
  const urlString = "/" + resourceType;
54
97
  if (options == null ? void 0 : options.apiVersion)
55
98
  apiVersion = options.apiVersion;
56
99
  const apiMessage = apiVersion ? `Using DHIS2 api version ${apiVersion}` : "Using latest available version of the DHIS2 api on this server.";
57
100
  console.log(apiMessage);
58
- const url = buildUrl(urlString, hostUrl, apiVersion);
101
+ const pathSuffix = apiVersion ? `/${apiVersion}${urlString}` : `${urlString}`;
102
+ const urlPath = "/api" + pathSuffix;
59
103
  if (path)
60
- return `${url}/${path}`;
61
- return url;
104
+ return `${urlPath}/${path}`;
105
+ return urlPath;
106
+ }
107
+ var configureAuth = (auth, headers = {}) => {
108
+ if ("pat" in auth) {
109
+ Object.assign(headers, {
110
+ Authorization: `ApiToken ${auth.pat}`
111
+ });
112
+ } else if ("password" in auth) {
113
+ Object.assign(headers, makeBasicAuthHeader(auth.username, auth.password));
114
+ } else {
115
+ throw new Error(
116
+ "Invalid authorization credentials. Include an pat, username or password in state.configuration"
117
+ );
118
+ }
119
+ return headers;
120
+ };
121
+ async function request(configuration, requestData) {
122
+ const { hostUrl } = configuration;
123
+ const { method, path, options = {}, data = {} } = requestData;
124
+ const {
125
+ headers = { "content-type": "application/json" },
126
+ query = {},
127
+ parseAs = "json"
128
+ } = options;
129
+ if (options)
130
+ console.log(`with params: `, query);
131
+ const authHeaders = configureAuth(configuration, headers);
132
+ const opts = {
133
+ headers: {
134
+ ...authHeaders,
135
+ ...headers
136
+ },
137
+ query,
138
+ parseAs,
139
+ body: data,
140
+ baseUrl: hostUrl
141
+ };
142
+ return commonRequest(method, path, opts).then(logResponse);
62
143
  }
63
144
 
64
145
  // src/meta/helper.js
65
146
  var createHelper = (configuration = {}) => {
66
147
  const { username, password } = configuration;
67
- const get2 = (url) => axios({
148
+ const get3 = (url) => axios({
68
149
  url,
69
150
  headers: { "Content-Type": "application/json" },
70
151
  responseType: "json",
@@ -89,20 +170,24 @@ var createHelper = (configuration = {}) => {
89
170
  ];
90
171
  };
91
172
  const getOrgUnits = async () => {
92
- const url = generateUrl(configuration, {}, "organisationUnits");
93
- const response = await get2(url);
173
+ const url = prefixVersionToPath(configuration, {}, "organisationUnits");
174
+ const response = await get3(url);
94
175
  return response.data;
95
176
  };
96
177
  const getPrograms = () => {
97
178
  };
98
179
  const getTrackedEntityTypes = async () => {
99
- const url = generateUrl(configuration, {}, "trackedEntityTypes");
100
- const response = await get2(url);
180
+ const url = prefixVersionToPath(configuration, {}, "trackedEntityTypes");
181
+ const response = await get3(url);
101
182
  return response.data;
102
183
  };
103
184
  const getAttributes = async () => {
104
- const url = generateUrl(configuration, {}, "trackedEntityAttributes");
105
- const response = await get2(url);
185
+ const url = prefixVersionToPath(
186
+ configuration,
187
+ {},
188
+ "trackedEntityAttributes"
189
+ );
190
+ const response = await get3(url);
106
191
  return response.data;
107
192
  };
108
193
  return {
@@ -155,21 +240,16 @@ var metadata_default = metadata;
155
240
  var Adaptor_exports = {};
156
241
  __export(Adaptor_exports, {
157
242
  alterState: () => alterState,
158
- attr: () => attr,
159
243
  create: () => create,
160
244
  cursor: () => cursor,
161
245
  dataPath: () => dataPath,
162
246
  dataValue: () => dataValue,
163
247
  dateFns: () => dateFns,
164
248
  destroy: () => destroy,
165
- discover: () => discover,
166
- dv: () => dv,
167
249
  each: () => each,
168
250
  execute: () => execute,
169
251
  field: () => field,
170
252
  fields: () => fields,
171
- findAttributeValue: () => findAttributeValue,
172
- findAttributeValueById: () => findAttributeValueById,
173
253
  fn: () => fn,
174
254
  fnIf: () => fnIf,
175
255
  get: () => get,
@@ -177,48 +257,12 @@ __export(Adaptor_exports, {
177
257
  http: () => http,
178
258
  lastReferenceValue: () => lastReferenceValue,
179
259
  merge: () => merge,
180
- patch: () => patch,
181
- post: () => post,
182
260
  sourceValue: () => sourceValue,
183
261
  update: () => update,
184
262
  upsert: () => upsert
185
263
  });
186
- import axios3 from "axios";
187
264
  import { execute as commonExecute } from "@openfn/language-common";
188
- import { expandReferences, encode } from "@openfn/language-common/util";
189
- import _ from "lodash";
190
-
191
- // src/Client.js
192
- import axios2 from "axios";
193
- import Qs from "qs";
194
- function request({ username, password, pat }, axiosRequest) {
195
- const { method, url, params } = axiosRequest;
196
- console.log(`Sending ${method} request to ${url}`);
197
- if (params)
198
- console.log(`with params: `, params);
199
- const safeRedirect = ["get", "head", "options", "trace"].includes(
200
- method.toLowerCase()
201
- );
202
- const headers = {
203
- "Content-Type": "application/json"
204
- };
205
- let auth;
206
- if (pat) {
207
- headers.Authorization = `ApiToken ${pat}`;
208
- } else {
209
- auth = { username, password };
210
- }
211
- return axios2({
212
- headers,
213
- responseType: "json",
214
- auth,
215
- maxRedirects: safeRedirect ? 5 : 0,
216
- paramsSerializer: (params2) => Qs.stringify(params2, { arrayFormat: "repeat" }),
217
- ...axiosRequest
218
- });
219
- }
220
-
221
- // src/Adaptor.js
265
+ import { expandReferences, throwError } from "@openfn/language-common/util";
222
266
  import {
223
267
  alterState,
224
268
  dataPath,
@@ -236,7 +280,6 @@ import {
236
280
  merge,
237
281
  sourceValue
238
282
  } from "@openfn/language-common";
239
- var { indexOf } = _;
240
283
  function execute(...operations) {
241
284
  const initialState = {
242
285
  references: [],
@@ -267,91 +310,76 @@ function configMigrationHelper(state) {
267
310
  }
268
311
  return state;
269
312
  }
270
- axios3.interceptors.response.use(
271
- function(response) {
272
- var _a, _b;
273
- const contentType = (_a = response.headers["content-type"]) == null ? void 0 : _a.split(";")[0];
274
- const acceptHeaders = response.config.headers["Accept"].split(";")[0].split(",");
275
- if (response.config.method === "get" && response.config.responseType != "arraybuffer") {
276
- if (indexOf(acceptHeaders, contentType) === -1) {
277
- const newError = {
278
- status: 404,
279
- message: "Unexpected content returned",
280
- responseData: response.data
281
- };
282
- console.error(newError.message);
283
- return Promise.reject(newError);
284
- }
285
- }
286
- if (typeof (response == null ? void 0 : response.data) === "string" && contentType === ((_b = CONTENT_TYPES) == null ? void 0 : _b.json)) {
287
- try {
288
- response = { ...response, data: JSON.parse(response.data) };
289
- } catch (error) {
290
- console.warn("Non-JSON response detected, unable to parse.");
291
- }
313
+ function create(path, data, params = {}) {
314
+ return async (state) => {
315
+ var _a;
316
+ if (path === "tracker") {
317
+ throw new Error("Invalid resourceType. Use `tracker.import()` instead.");
292
318
  }
293
- return response;
294
- },
295
- function(error) {
296
- var _a, _b, _c, _d;
297
- if ((_a = error.config) == null ? void 0 : _a.auth)
298
- error.config.auth = "--REDACTED--";
299
- if ((_b = error.config) == null ? void 0 : _b.data)
300
- error.config.data = "--REDACTED--";
301
- const details = (_c = error.response) == null ? void 0 : _c.data;
302
- console.error(error.message || "That didn't work.");
303
- if (details)
304
- console.log(JSON.stringify(details, null, 2));
305
- return Promise.reject({
306
- request: error.config,
307
- message: error.message,
308
- response: (_d = error.response) == null ? void 0 : _d.data
309
- });
310
- }
311
- );
312
- function create(resourceType, data, options = {}, callback = (s) => s) {
313
- return (state) => {
314
- console.log(`Preparing create operation...`);
315
- const [resolvedResourceType, resolvedData, resolvedOptions] = expandReferences(state, resourceType, data, options);
316
- const { params, requestConfig } = resolvedOptions;
319
+ const [resolvedPath, resolvedData, resolvedParams] = expandReferences(
320
+ state,
321
+ path,
322
+ data,
323
+ params
324
+ );
317
325
  const { configuration } = state;
318
- let promise;
319
- if (shouldUseNewTracker(resolvedResourceType)) {
320
- promise = callNewTracker(
326
+ let response;
327
+ if (shouldUseNewTracker(resolvedPath)) {
328
+ response = await callNewTracker(
321
329
  "create",
322
330
  configuration,
323
- resolvedOptions,
324
- resolvedResourceType,
331
+ {
332
+ query: resolvedParams
333
+ },
334
+ resolvedPath,
325
335
  resolvedData
326
336
  );
327
337
  } else {
328
- promise = request(configuration, {
329
- method: "post",
330
- url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
331
- params,
332
- data: resolvedData,
333
- ...requestConfig
338
+ response = await request(configuration, {
339
+ method: "POST",
340
+ path: prefixVersionToPath(configuration, {}, resolvedPath),
341
+ options: {
342
+ query: resolvedParams
343
+ },
344
+ data: resolvedData
334
345
  });
335
346
  }
336
- return promise.then((result) => {
337
- const details = `with response ${JSON.stringify(result.data, null, 2)}`;
338
- console.log(`Created ${resolvedResourceType} ${details}`);
339
- const { location } = result.headers;
340
- if (location)
341
- console.log(`Record available @ ${location}`);
342
- return handleResponse(result, state, callback);
347
+ const details = `with response ${JSON.stringify(
348
+ (_a = response.body) == null ? void 0 : _a.message,
349
+ null,
350
+ 2
351
+ )}`;
352
+ console.log(`Created ${resolvedPath} ${details}`);
353
+ const { location } = response.headers;
354
+ if (location)
355
+ console.log(`Record available @ ${location}`);
356
+ return handleResponse(response, state);
357
+ };
358
+ }
359
+ function get(path, params = {}) {
360
+ return async (state) => {
361
+ const [resolvedPath, resolvedParams] = expandReferences(
362
+ state,
363
+ path,
364
+ params
365
+ );
366
+ const response = await request(state.configuration, {
367
+ method: "GET",
368
+ path: prefixVersionToPath(state.configuration, {}, resolvedPath),
369
+ options: { query: resolvedParams }
343
370
  });
371
+ console.log(`Retrieved ${resolvedPath}`);
372
+ return handleResponse(response, state);
344
373
  };
345
374
  }
346
- function update(resourceType, path, data, options = {}, callback = (s) => s) {
347
- return (state) => {
375
+ function update(resourceType, path, data, options = {}) {
376
+ return async (state) => {
348
377
  console.log(`Preparing update operation...`);
349
378
  const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = expandReferences(state, resourceType, path, data, options);
350
- const { requestConfig } = resolvedOptions;
351
379
  const { configuration } = state;
352
- let promise;
380
+ let response;
353
381
  if (shouldUseNewTracker(resolvedResourceType)) {
354
- promise = callNewTracker(
382
+ response = await callNewTracker(
355
383
  "update",
356
384
  configuration,
357
385
  resolvedOptions,
@@ -359,73 +387,29 @@ function update(resourceType, path, data, options = {}, callback = (s) => s) {
359
387
  resolvedData
360
388
  );
361
389
  } else {
362
- promise = request(configuration, {
363
- method: "put",
364
- url: generateUrl(
390
+ response = await request(configuration, {
391
+ method: "PUT",
392
+ path: prefixVersionToPath(
365
393
  configuration,
366
394
  resolvedOptions,
367
395
  resolvedResourceType,
368
396
  resolvedPath
369
397
  ),
370
- options,
371
- data: resolvedData,
372
- ...requestConfig
398
+ options: resolvedOptions,
399
+ data: resolvedData
373
400
  });
374
401
  }
375
- return promise.then((result) => {
376
- console.log(`Updated ${resolvedResourceType} at ${resolvedPath}`);
377
- return handleResponse(result, state, callback);
378
- });
402
+ console.log(`Updated ${resolvedResourceType} at ${resolvedPath}`);
403
+ return handleResponse(response, state);
379
404
  };
380
405
  }
381
- function get(resourceType, query, options = {}, callback = (s) => s) {
382
- return (state) => {
383
- console.log("Preparing get operation...");
384
- const [resolvedResourceType, resolvedQuery, resolvedOptions] = expandReferences(state, resourceType, query, options);
385
- const { params, requestConfig, asBase64 = false } = resolvedOptions;
406
+ function upsert(resourceType, query, data, options = {}) {
407
+ return async (state) => {
408
+ const [resolvedResourceType, resolvedOptions, resolvedData, resolvedQuery] = expandReferences(state, resourceType, options, data, query);
409
+ let response;
386
410
  const { configuration } = state;
387
- return request(configuration, {
388
- method: "get",
389
- url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
390
- params: {
391
- ...resolvedQuery,
392
- ...params
393
- },
394
- responseType: asBase64 ? "arraybuffer" : "json",
395
- ...requestConfig
396
- }).then((result) => {
397
- console.log(`Retrieved ${resolvedResourceType}`);
398
- const response = asBase64 ? { data: encode(result.data) } : result;
399
- return handleResponse(response, state, callback);
400
- });
401
- };
402
- }
403
- function post(resourceType, data, query, options = {}, callback = (s) => s) {
404
- return (state) => {
405
- console.log("Preparing post operation...");
406
- const [resolvedResourceType, resolvedQuery, resolvedOptions, resolvedData] = expandReferences(state, resourceType, query, options, data);
407
- const { params, requestConfig } = resolvedOptions;
408
- const { configuration } = state;
409
- return request(configuration, {
410
- method: "post",
411
- url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
412
- params: { ...resolvedQuery, ...params },
413
- responseType: "json",
414
- data: resolvedData,
415
- ...requestConfig
416
- }).then((result) => {
417
- console.log(`Created ${resolvedResourceType}`);
418
- return handleResponse(result, state, callback);
419
- });
420
- };
421
- }
422
- function upsert(resourceType, query, data, options = {}, callback = (s) => s) {
423
- return (state) => {
424
- const [resolvedResourceType, resolvedOptions, resolvedData] = expandReferences(state, resourceType, options, data);
425
- let promise;
426
411
  if (shouldUseNewTracker(resolvedResourceType)) {
427
- const { configuration } = state;
428
- promise = callNewTracker(
412
+ response = await callNewTracker(
429
413
  "create_and_update",
430
414
  configuration,
431
415
  resolvedOptions,
@@ -434,128 +418,67 @@ function upsert(resourceType, query, data, options = {}, callback = (s) => s) {
434
418
  );
435
419
  } else {
436
420
  console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
437
- promise = get(
438
- resourceType,
439
- query,
440
- options
441
- )(state).then((resp) => {
442
- const resources = resp.data[resourceType];
443
- if (resources.length > 1) {
444
- throw new RangeError(
445
- `Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`
446
- );
447
- } else if (resources.length <= 0) {
448
- return create(resourceType, data, options)(state);
449
- } else {
450
- const path = resources[0][selectId(resourceType)];
451
- return update(resourceType, path, data, options)(state);
421
+ response = await request(configuration, {
422
+ method: "GET",
423
+ path: prefixVersionToPath(
424
+ configuration,
425
+ resolvedOptions,
426
+ resolvedResourceType
427
+ ),
428
+ options: {
429
+ ...resolvedOptions,
430
+ query: {
431
+ ...resolvedQuery
432
+ }
452
433
  }
453
434
  });
454
- }
455
- return promise.then((result) => {
456
- console.log(`Performed a "composed upsert" on ${resourceType}`);
457
- return handleResponse(result, state, callback);
458
- });
459
- };
460
- }
461
- function discover(httpMethod, endpoint) {
462
- return (state) => {
463
- console.log(
464
- `Discovering query/import parameters for ${httpMethod} on ${endpoint}`
465
- );
466
- return axios3.get(
467
- "https://dhis2.github.io/dhis2-api-specification/spec/metadata_openapi.json",
468
- {
469
- transformResponse: [
470
- (data) => {
471
- let tempData = JSON.parse(data);
472
- let filteredData = tempData.paths[endpoint][httpMethod];
473
- return {
474
- ...filteredData,
475
- parameters: filteredData.parameters.reduce(
476
- (acc, currentValue) => {
477
- let index = currentValue["$ref"].lastIndexOf("/") + 1;
478
- let paramRef = currentValue["$ref"].slice(index);
479
- let param = tempData.components.parameters[paramRef];
480
- if (param.schema["$ref"]) {
481
- let schemaRefIndex = param.schema["$ref"].lastIndexOf("/") + 1;
482
- let schemaRef = param.schema["$ref"].slice(schemaRefIndex);
483
- param.schema = tempData.components.schemas[schemaRef];
484
- }
485
- param.schema = JSON.stringify(param.schema);
486
- let descIndex;
487
- if (indexOf(param.description, ",") === -1 && indexOf(param.description, ".") > -1)
488
- descIndex = indexOf(param.description, ".");
489
- else if (indexOf(param.description, ",") > -1 && indexOf(param.description, ".") > -1) {
490
- descIndex = indexOf(param.description, ".") < indexOf(param.description, ",") ? indexOf(param.description, ".") : indexOf(param.description, ",");
491
- } else {
492
- descIndex = param.description.length;
493
- }
494
- param.description = param.description.slice(0, descIndex);
495
- acc[paramRef] = param;
496
- return acc;
497
- },
498
- {}
499
- )
500
- };
501
- }
502
- ]
435
+ const resources = response.body[resourceType];
436
+ if (resources.length > 1) {
437
+ throwError(409, {
438
+ description: "Upsert failed: Multiple records found for a non-unique attribute.",
439
+ fix: "Ensure the attribute is unique or modify the request to target a single record.",
440
+ error: "Conflict"
441
+ });
442
+ } else if (resources.length <= 0) {
443
+ console.log(`Preparing create operation...`);
444
+ response = await request(configuration, {
445
+ method: "POST",
446
+ path: prefixVersionToPath(
447
+ configuration,
448
+ resolvedOptions,
449
+ resolvedResourceType
450
+ ),
451
+ options: resolvedOptions,
452
+ data: resolvedData
453
+ });
454
+ } else {
455
+ const path = resources[0][selectId(resourceType)];
456
+ console.log(`Preparing update operation...`);
457
+ response = await request(configuration, {
458
+ method: "PUT",
459
+ path: prefixVersionToPath(
460
+ configuration,
461
+ resolvedOptions,
462
+ resolvedResourceType,
463
+ path
464
+ ),
465
+ options: resolvedOptions,
466
+ data: resolvedData
467
+ });
503
468
  }
504
- ).then((result) => {
505
- console.log(
506
- ` =======================================================================================
507
- Query Parameters for ${httpMethod} on ${endpoint} [${result.data.description ?? "<description_missing>"}]
508
- =======================================================================================`
509
- );
510
- console.table(result.data.parameters, [
511
- "in",
512
- "required",
513
- "description"
514
- ]);
515
- console.table(result.data.parameters, ["schema"]);
516
- console.log(
517
- `=========================================Responses===============================
518
- ${prettyJson(
519
- result.data.responses
520
- )}
521
- =======================================================================================`
522
- );
523
- return { ...state, data: result.data };
524
- });
525
- };
526
- }
527
- function patch(resourceType, path, data, options = {}, callback = (s) => s) {
528
- return (state) => {
529
- console.log("Preparing patch operation...");
530
- const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = expandReferences(state, resourceType, path, data, options);
531
- const { params, requestConfig } = resolvedOptions;
532
- const { configuration } = state;
533
- return request(configuration, {
534
- method: "patch",
535
- url: generateUrl(
536
- configuration,
537
- resolvedOptions,
538
- resolvedResourceType,
539
- resolvedPath
540
- ),
541
- params,
542
- data: resolvedData,
543
- ...requestConfig
544
- }).then((result) => {
545
- console.log(`Patched ${resolvedResourceType} at ${resolvedPath}`);
546
- return handleResponse(result, state, callback);
547
- });
469
+ }
470
+ console.log(`Performed a "composed upsert" on ${resourceType}`);
471
+ return handleResponse(response, state);
548
472
  };
549
473
  }
550
- function destroy(resourceType, path, data = null, options = {}, callback = false) {
551
- return (state) => {
474
+ function destroy(resourceType, path, data = null, options = {}) {
475
+ return async (state) => {
552
476
  console.log("Preparing destroy operation...");
553
477
  const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = expandReferences(state, resourceType, path, data, options);
554
- const { params, requestConfig } = resolvedOptions;
555
478
  const { configuration } = state;
556
- let promise;
479
+ let response;
557
480
  if (shouldUseNewTracker(resolvedResourceType)) {
558
- promise = callNewTracker(
481
+ response = await callNewTracker(
559
482
  "delete",
560
483
  configuration,
561
484
  resolvedOptions,
@@ -563,43 +486,23 @@ function destroy(resourceType, path, data = null, options = {}, callback = false
563
486
  resolvedData
564
487
  );
565
488
  } else {
566
- promise = request({
567
- method: "delete",
568
- url: generateUrl(
489
+ response = await request(configuration, {
490
+ method: "DELETE",
491
+ path: prefixVersionToPath(
569
492
  configuration,
570
493
  resolvedOptions,
571
494
  resolvedResourceType,
572
495
  resolvedPath
573
496
  ),
574
- params,
575
- resolvedData,
576
- ...requestConfig
497
+ options: resolvedOptions,
498
+ data: resolvedData
577
499
  });
578
500
  }
579
- return promise.then((result) => {
580
- console.log(`Deleted ${resolvedResourceType} at ${resolvedPath}`);
581
- return handleResponse(result, state, callback);
582
- });
501
+ console.log(`Deleted ${resolvedResourceType} at ${resolvedPath}`);
502
+ return handleResponse(response, state);
583
503
  };
584
504
  }
585
- function findAttributeValueById(trackedEntity, attributeUid) {
586
- var _a, _b;
587
- return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find((a) => (a == null ? void 0 : a.attribute) == attributeUid)) == null ? void 0 : _b.value;
588
- }
589
- function findAttributeValue(trackedEntity, attributeDisplayName) {
590
- var _a, _b;
591
- return (_b = (_a = trackedEntity == null ? void 0 : trackedEntity.attributes) == null ? void 0 : _a.find(
592
- (a) => (a == null ? void 0 : a.displayName.toLowerCase()) == attributeDisplayName.toLowerCase()
593
- )) == null ? void 0 : _b.value;
594
- }
595
- function attr(attribute, value) {
596
- return { attribute, value };
597
- }
598
- function dv(dataElement, value) {
599
- return { dataElement, value };
600
- }
601
505
  function callNewTracker(type = "update", configuration, options, resourceType, data = {}) {
602
- const { params, requestConfig, ...opts } = options;
603
506
  let importStrategy;
604
507
  switch (type) {
605
508
  case "create":
@@ -615,26 +518,182 @@ function callNewTracker(type = "update", configuration, options, resourceType, d
615
518
  importStrategy = "CREATE_AND_UPDATE";
616
519
  }
617
520
  return request(configuration, {
618
- method: "post",
619
- url: generateUrl(
620
- configuration,
621
- {
622
- ...opts,
521
+ method: "POST",
522
+ path: prefixVersionToPath(configuration, options, "tracker"),
523
+ options: {
524
+ ...options,
525
+ query: {
526
+ ...options.query,
527
+ async: false,
623
528
  importStrategy
624
- },
625
- "tracker"
626
- ),
627
- params: { async: false, ...params },
628
- data: ensureArray(data, resourceType),
629
- ...requestConfig
529
+ }
530
+ },
531
+ data: ensureArray(data, resourceType)
630
532
  });
631
533
  }
632
534
 
535
+ // src/http.js
536
+ var http_exports = {};
537
+ __export(http_exports, {
538
+ get: () => get2,
539
+ patch: () => patch,
540
+ post: () => post,
541
+ request: () => request2
542
+ });
543
+ import { expandReferences as expandReferences2 } from "@openfn/language-common/util";
544
+ function get2(path, options = {}) {
545
+ return async (state) => {
546
+ console.log("Preparing get operation...");
547
+ const [resolvedPath, resolvedOptions] = expandReferences2(
548
+ state,
549
+ path,
550
+ options
551
+ );
552
+ const { parseAs } = resolvedOptions;
553
+ const response = await request(state.configuration, {
554
+ method: "GET",
555
+ path: prefixVersionToPath(
556
+ state.configuration,
557
+ resolvedOptions,
558
+ resolvedPath
559
+ ),
560
+ options: resolvedOptions
561
+ });
562
+ return handleHttpResponse(response, state);
563
+ };
564
+ }
565
+ function post(path, data, options = {}) {
566
+ return async (state) => {
567
+ console.log("Preparing post operation...");
568
+ const [resolvedPath, resolvedOptions, resolvedData] = expandReferences2(
569
+ state,
570
+ path,
571
+ options,
572
+ data
573
+ );
574
+ const { configuration } = state;
575
+ let response;
576
+ response = await request(configuration, {
577
+ method: "POST",
578
+ path: prefixVersionToPath(
579
+ configuration,
580
+ resolvedOptions,
581
+ resolvedPath
582
+ ),
583
+ options: resolvedOptions,
584
+ data: resolvedData
585
+ });
586
+ return handleHttpResponse(response, state);
587
+ };
588
+ }
589
+ function patch(resourceType, path, data, options = {}) {
590
+ return async (state) => {
591
+ console.log("Preparing patch operation...");
592
+ const [resolvedResourceType, resolvedPath, resolvedData, resolvedOptions] = expandReferences2(state, resourceType, path, data, options);
593
+ const { configuration } = state;
594
+ let response;
595
+ response = await request(configuration, {
596
+ method: "PATCH",
597
+ path: prefixVersionToPath(
598
+ configuration,
599
+ resolvedOptions,
600
+ resolvedResourceType,
601
+ resolvedPath
602
+ ),
603
+ options: resolvedOptions,
604
+ data: resolvedData
605
+ });
606
+ return handleHttpResponse(response, state);
607
+ };
608
+ }
609
+ function request2(method, path, options = {}) {
610
+ return async (state) => {
611
+ console.log(`Preparing a ${method.toLowerCase()} operation...`);
612
+ const [resolvedMethod, resolvedPath, resolvedOptions = {}] = expandReferences2(state, method, path, options);
613
+ const { data } = resolvedOptions;
614
+ const { configuration } = state;
615
+ let response;
616
+ response = await request(configuration, {
617
+ method: resolvedMethod,
618
+ path: prefixVersionToPath(
619
+ configuration,
620
+ resolvedOptions,
621
+ resolvedPath
622
+ ),
623
+ options: resolvedOptions,
624
+ data
625
+ });
626
+ return handleHttpResponse(response, state);
627
+ };
628
+ }
629
+
630
+ // src/tracker.js
631
+ var tracker_exports = {};
632
+ __export(tracker_exports, {
633
+ export: () => _export,
634
+ import: () => _import
635
+ });
636
+ import { expandReferences as expandReferences3 } from "@openfn/language-common/util";
637
+ function _import(strategy, payload, options = {}) {
638
+ return async (state) => {
639
+ console.log("Preparing tracker import operation...");
640
+ const [resolvedStrategy, resolvedPayload, resolvedOptions] = expandReferences3(state, strategy, payload, options);
641
+ const { apiVersion, parseAs, ...query } = resolvedOptions;
642
+ const response = await request(state.configuration, {
643
+ method: "POST",
644
+ path: prefixVersionToPath(
645
+ state.configuration,
646
+ {
647
+ ...resolvedOptions,
648
+ resolvedStrategy
649
+ },
650
+ "tracker"
651
+ ),
652
+ options: {
653
+ apiVersion,
654
+ parseAs,
655
+ query: {
656
+ ...query,
657
+ async: false
658
+ }
659
+ },
660
+ data: resolvedPayload
661
+ });
662
+ return handleHttpResponse(response, state);
663
+ };
664
+ }
665
+ function _export(path, query, options = {}) {
666
+ return async (state) => {
667
+ console.log("Preparing tracker export operation...");
668
+ const [resolvedPath, resolvedQuery, resolvedOptions] = expandReferences3(
669
+ state,
670
+ path,
671
+ query,
672
+ options
673
+ );
674
+ const response = await request(state.configuration, {
675
+ method: "GET",
676
+ path: prefixVersionToPath(
677
+ state.configuration,
678
+ resolvedOptions,
679
+ `tracker/${resolvedPath}`
680
+ ),
681
+ options: {
682
+ ...resolvedOptions,
683
+ query: {
684
+ ...resolvedQuery,
685
+ async: false
686
+ }
687
+ }
688
+ });
689
+ return handleHttpResponse(response, state);
690
+ };
691
+ }
692
+
633
693
  // src/index.js
634
694
  var src_default = Adaptor_exports;
635
695
  export {
636
696
  alterState,
637
- attr,
638
697
  create,
639
698
  cursor,
640
699
  dataPath,
@@ -642,25 +701,21 @@ export {
642
701
  dateFns,
643
702
  src_default as default,
644
703
  destroy,
645
- discover,
646
- dv,
647
704
  each,
648
705
  execute,
649
706
  field,
650
707
  fields,
651
- findAttributeValue,
652
- findAttributeValueById,
653
708
  fn,
654
709
  fnIf,
655
710
  get,
656
711
  group,
657
- http,
712
+ http_exports as http,
658
713
  lastReferenceValue,
659
714
  merge,
660
715
  metadata_default as metadata,
661
- patch,
662
- post,
663
716
  sourceValue,
717
+ tracker_exports as tracker,
664
718
  update,
665
- upsert
719
+ upsert,
720
+ util_exports as util
666
721
  };