@openfn/language-ghana-bdr 0.2.1 → 1.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/README.md CHANGED
@@ -17,6 +17,12 @@ View the
17
17
  [configuration-schema](https://docs.openfn.org/adaptors/packages/ghana-bdr-configuration-schema/)
18
18
  for required and optional `configuration` properties.
19
19
 
20
+ The adaptor uses token-based authentication:
21
+
22
+ - Provide your base URL in `configuration.baseUrl` (e.g.,
23
+ https://bdrbeta.npontu.com)
24
+ - Provide your long-lived API token in `configuration.token`
25
+
20
26
  ## Development
21
27
 
22
28
  Clone the [adaptors monorepo](https://github.com/OpenFn/adaptors). Follow the
package/ast.json CHANGED
@@ -115,16 +115,105 @@
115
115
  "valid": true
116
116
  },
117
117
  {
118
- "name": "sendBirthNotification",
118
+ "name": "request",
119
+ "params": [
120
+ "method",
121
+ "path",
122
+ "body",
123
+ "options"
124
+ ],
125
+ "docs": {
126
+ "description": "Make a general HTTP request to the BDR API",
127
+ "tags": [
128
+ {
129
+ "title": "example",
130
+ "description": "request(\"POST\", \"/api/v1/UserManagementService/integrations/utility\", {\n type: \"regions\",\n});"
131
+ },
132
+ {
133
+ "title": "function",
134
+ "description": null,
135
+ "name": null
136
+ },
137
+ {
138
+ "title": "public",
139
+ "description": null,
140
+ "type": null
141
+ },
142
+ {
143
+ "title": "param",
144
+ "description": "HTTP method to use",
145
+ "type": {
146
+ "type": "NameExpression",
147
+ "name": "string"
148
+ },
149
+ "name": "method"
150
+ },
151
+ {
152
+ "title": "param",
153
+ "description": "Path to resource",
154
+ "type": {
155
+ "type": "NameExpression",
156
+ "name": "string"
157
+ },
158
+ "name": "path"
159
+ },
160
+ {
161
+ "title": "param",
162
+ "description": "Object which will be attached to the request body",
163
+ "type": {
164
+ "type": "OptionalType",
165
+ "expression": {
166
+ "type": "NameExpression",
167
+ "name": "object"
168
+ }
169
+ },
170
+ "name": "body"
171
+ },
172
+ {
173
+ "title": "param",
174
+ "description": "Optional request options, e.g. query and headers",
175
+ "type": {
176
+ "type": "OptionalType",
177
+ "expression": {
178
+ "type": "NameExpression",
179
+ "name": "object"
180
+ }
181
+ },
182
+ "name": "options"
183
+ },
184
+ {
185
+ "title": "returns",
186
+ "description": null,
187
+ "type": {
188
+ "type": "NameExpression",
189
+ "name": "Operation"
190
+ }
191
+ },
192
+ {
193
+ "title": "state",
194
+ "description": "{HttpState}"
195
+ }
196
+ ]
197
+ },
198
+ "valid": true
199
+ },
200
+ {
201
+ "name": "createBirthRecord",
119
202
  "params": [
120
203
  "data"
121
204
  ],
122
205
  "docs": {
123
- "description": "Generate a birth certificate",
206
+ "description": "Create a birth record. `child_file_birth_evidence_data` takes an array of\nbase64-encoded data URIs (truncated in the example below).",
124
207
  "tags": [
125
208
  {
126
209
  "title": "example",
127
- "description": "sendBirthNotification({\n registry_code: 'abc123',\n child: {},\n mother: {},\n father: {},\n})"
210
+ "description": "createBirthRecord($.data);",
211
+ "caption": "Create a birth record from data on state"
212
+ },
213
+ {
214
+ "title": "example",
215
+ "description": "createBirthRecord({\n status: \"COMPLETE\",\n region_id: 4348,\n district_id: 338,\n type_of_birth: \"SINGLETON\",\n informant_type: \"MOTHER\",\n informant_national_id_type: \"GHANA CARD\",\n informant_national_id_number: \"34454344\",\n informant_first_name: \"David\",\n informant_middle_name: \"\",\n informant_last_name: \"Godson\",\n informant_region_id: 4348,\n informant_district_id: 338,\n informant_residential_address: \"Dansoman\",\n informant_phone_number: \"2335648498309\",\n child_first_name: \"Francis\",\n child_middle_name: \"\",\n child_last_name: \"Benzoic\",\n child_gender: \"MALE\",\n child_dob: \"2025-06-26\",\n child_place_of_birth: \"HOSPITAL\",\n child_birth_attendant: \"MID-WIFE\",\n child_birth_institution: \"Ludra Hospital\",\n child_town: \"Ashaiman\",\n child_house_no: \"H/F286\",\n child_street_name: \"Ashaiman Newtown\",\n mother_national_id_type: \"GHANA CARD\",\n mother_national_id_number: \"32432423433\",\n mother_phone_number: \"2335456823893\",\n mother_first_name: \"Adwoa\",\n mother_middle_name: \"\",\n mother_last_name: \"Godson\",\n mother_age: 30,\n mother_marital_status: \"MARRIED\",\n mother_previous_birth_no: 50,\n mother_occupation: \"teacher\",\n mother_educational_level: \"DIPLOMA\",\n mother_region_id: 4348,\n mother_district_id: 338,\n mother_town: \"Accra\",\n mother_religion: \"CHRISTIAN\",\n mother_residence: \"Tamale\",\n mother_nationality: \"GHANA\",\n doubtful_maternity: 0,\n father_national_id_type: \"GHANA CARD\",\n father_national_id_number: \"32432423433\",\n father_phone_number: \"233548791223\",\n father_first_name: \"David\",\n father_middle_name: \"\",\n father_last_name: \"Godson\",\n father_age: 33,\n father_marital_status: \"MARRIED\",\n father_children_no: 5,\n father_occupation: \"Doctor\",\n father_educational_level: \"DIPLOMA\",\n father_region_id: 4348,\n father_district_id: 338,\n father_town: \"Tema\",\n father_residence: \"Tema\",\n father_nationality: \"GHANA\",\n father_religion: \"CHRISTIAN\",\n doubtful_paternity: 0,\n child_file_birth_evidence_name: [\"Physics.jpg\"],\n child_file_birth_evidence_data: [\"data:image/jpeg;base64,/9j/4QAYRXhpZg...\"]\n})",
216
+ "caption": "Create a birth record with a full payload"
128
217
  },
129
218
  {
130
219
  "title": "function",
@@ -138,7 +227,7 @@
138
227
  },
139
228
  {
140
229
  "title": "param",
141
- "description": "body data to append to the request. JSON will be converted to a string (but a content-type header will not be attached to the request).",
230
+ "description": "body data to append to the request. JSON will be converted to a string.",
142
231
  "type": {
143
232
  "type": "NameExpression",
144
233
  "name": "object"
@@ -4,26 +4,21 @@
4
4
  "baseUrl": {
5
5
  "title": "Base URL",
6
6
  "type": "string",
7
- "description": "The base URL (http://www.example.com)",
7
+ "description": "The base URL of the BDR API (e.g., https://bdrbeta.npontu.com)",
8
8
  "format": "uri",
9
9
  "minLength": 1,
10
- "examples": ["https://example.com"]
10
+ "examples": ["https://bdrbeta.npontu.com"]
11
11
  },
12
- "username": {
13
- "title": "Username",
12
+ "token": {
13
+ "title": "API Token",
14
14
  "type": "string",
15
- "description": "Username",
16
- "examples": ["test@openfn.org"]
17
- },
18
- "password": {
19
- "title": "Password",
20
- "type": "string",
21
- "description": "Password",
15
+ "description": "Long-lived API consumer token for authentication",
22
16
  "writeOnly": true,
23
- "examples": ["@some(!)Str0ngp4ss0w0rd"]
17
+ "minLength": 1,
18
+ "examples": ["your-long-lived-api-token-here"]
24
19
  }
25
20
  },
26
21
  "type": "object",
27
22
  "additionalProperties": true,
28
- "required": ["password", "username", "baseUrl"]
23
+ "required": ["baseUrl", "token"]
29
24
  }
package/dist/index.cjs CHANGED
@@ -1,8 +1,6 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
5
  var __export = (target, all) => {
8
6
  for (var name in all)
@@ -16,16 +14,13 @@ var __copyProps = (to, from, except, desc) => {
16
14
  }
17
15
  return to;
18
16
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
21
- mod
22
- ));
23
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
18
 
25
19
  // src/index.js
26
20
  var src_exports = {};
27
21
  __export(src_exports, {
28
22
  combine: () => import_language_common3.combine,
23
+ createBirthRecord: () => createBirthRecord,
29
24
  cursor: () => import_language_common3.cursor,
30
25
  dataPath: () => import_language_common3.dataPath,
31
26
  dataValue: () => import_language_common3.dataValue,
@@ -42,7 +37,7 @@ __export(src_exports, {
42
37
  log: () => import_language_common3.log,
43
38
  merge: () => import_language_common3.merge,
44
39
  post: () => post,
45
- sendBirthNotification: () => sendBirthNotification,
40
+ request: () => request2,
46
41
  sourceValue: () => import_language_common3.sourceValue
47
42
  });
48
43
  module.exports = __toCommonJS(src_exports);
@@ -51,6 +46,7 @@ module.exports = __toCommonJS(src_exports);
51
46
  var Adaptor_exports = {};
52
47
  __export(Adaptor_exports, {
53
48
  combine: () => import_language_common3.combine,
49
+ createBirthRecord: () => createBirthRecord,
54
50
  cursor: () => import_language_common3.cursor,
55
51
  dataPath: () => import_language_common3.dataPath,
56
52
  dataValue: () => import_language_common3.dataValue,
@@ -66,228 +62,102 @@ __export(Adaptor_exports, {
66
62
  log: () => import_language_common3.log,
67
63
  merge: () => import_language_common3.merge,
68
64
  post: () => post,
69
- sendBirthNotification: () => sendBirthNotification,
65
+ request: () => request2,
70
66
  sourceValue: () => import_language_common3.sourceValue
71
67
  });
72
68
  var import_language_common2 = require("@openfn/language-common");
73
69
 
74
- // src/util.js
75
- var import_undici = __toESM(require("undici"), 1);
76
- var import_node_path = __toESM(require("path"), 1);
70
+ // src/Utils.js
77
71
  var import_util = require("@openfn/language-common/util");
78
72
  var import_language_common = require("@openfn/language-common");
79
- var client;
80
- var getClient = (baseUrl) => {
81
- if (baseUrl) {
82
- const url = new URL(baseUrl);
83
- client = new import_undici.default.Client(url.origin);
73
+ var TOKEN_PATH = "/api/v1/UserManagementService/integrations/auth/token";
74
+ var getAccessToken = async (state) => {
75
+ var _a;
76
+ const { auth } = state;
77
+ if ((auth == null ? void 0 : auth.accessToken) && auth.expiresAt > Date.now()) {
78
+ return auth;
84
79
  }
85
- return client;
86
- };
87
- var setMockClient = (mockClient) => {
88
- client = mockClient;
89
- };
90
- var validateRequestBody = (request2, sample) => {
91
- const sampleKeys = Object.keys(sample);
92
- const requestKeys = Object.keys(request2);
93
- for (const key of sampleKeys) {
94
- if (!requestKeys.includes(key)) {
95
- console.log("Key missing:", key);
96
- return false;
97
- }
98
- if (typeof sample[key] != typeof request2[key]) {
99
- console.log("Key with wrong value type:", key);
100
- return false;
101
- }
102
- if (typeof sample[key] === "object" && sample[key] !== null) {
103
- if (!validateRequestBody(request2[key], sample[key])) {
104
- console.log("Failed check at:", key);
105
- return false;
106
- }
80
+ const { baseUrl, token } = state.configuration;
81
+ if (!token) {
82
+ throw new Error("Missing configuration.token (long-lived API token)");
83
+ }
84
+ const response = await (0, import_util.request)("POST", TOKEN_PATH, {
85
+ baseUrl,
86
+ parseAs: "json",
87
+ headers: {
88
+ "Content-Type": "application/json",
89
+ Accept: "application/json",
90
+ Token: token
107
91
  }
92
+ });
93
+ (0, import_util.logResponse)(response);
94
+ const { access_token, expires_in } = ((_a = response.body) == null ? void 0 : _a.api_data) ?? {};
95
+ if (!access_token) {
96
+ (0, import_util.throwError)("BDR_AUTH_ERROR", {
97
+ description: "Malformed token response: missing access_token. The API returned a 200 but the response did not contain a valid token."
98
+ });
99
+ }
100
+ if (!expires_in || typeof expires_in !== "number") {
101
+ (0, import_util.throwError)("BDR_AUTH_ERROR", {
102
+ description: "Malformed token response: missing or invalid expires_in."
103
+ });
108
104
  }
109
- return true;
105
+ return {
106
+ accessToken: access_token,
107
+ expiresAt: Date.now() + expires_in * 1e3 - 3e4
108
+ };
110
109
  };
111
- var prepareNextState = async (state, response) => {
110
+ var prepareNextState = (state, response) => {
112
111
  const { body, ...responseWithoutBody } = response;
113
- const result = await body.json();
114
- const resultAsJson = JSON.parse(result);
115
- if (!state.references) {
116
- state.references = [];
117
- }
118
- const nextState = {
119
- ...(0, import_language_common.composeNextState)(state, resultAsJson),
112
+ return {
113
+ ...(0, import_language_common.composeNextState)(state, body),
120
114
  response: responseWithoutBody
121
115
  };
122
- return nextState;
123
116
  };
124
- var request = (path, options) => {
117
+ function request(path, options) {
125
118
  return async (state) => {
126
- const { baseUrl, username, password } = state.configuration;
127
- getClient(baseUrl);
128
- const basePath = baseUrl ? new URL(baseUrl).pathname : "/";
129
- const [resolvedPath, resolvedoptions] = (0, import_util.expandReferences)(
119
+ const [resolvedPath, resolvedOptions] = (0, import_util.expandReferences)(
130
120
  state,
131
121
  path,
132
122
  options
133
123
  );
124
+ const { baseUrl } = state.configuration;
134
125
  const {
135
126
  data,
136
- headers = { "content-type": "application/json" },
127
+ headers = {},
137
128
  method = "POST",
138
129
  query,
139
130
  ...otherOptions
140
- } = resolvedoptions;
141
- const safePath = resolvedPath ? import_node_path.default.join(basePath, resolvedPath) : basePath;
142
- const args = {
143
- path: safePath,
144
- data,
145
- headers: {
146
- ...headers
147
- },
148
- method,
149
- query,
150
- ...otherOptions
151
- };
152
- if (data.username || data.password) {
153
- (0, import_util.throwError)(
154
- "Please don't supply `username` and `password` in your request body. The adaptor will append it automatically."
155
- );
156
- }
157
- if (data) {
158
- args.body = JSON.stringify(
159
- JSON.stringify({
160
- ...data,
161
- username,
162
- password
163
- })
164
- );
165
- args.data = { ...data, username, password };
166
- }
167
- const response = await client.request(args);
168
- if (response.statusCode >= 400) {
169
- (0, import_util.throwError)("BDR_ERROR", {
170
- code: response.statusCode,
171
- description: response.statusMessage,
172
- body: await response.body.text()
173
- });
174
- }
175
- (0, import_util.logResponse)(response);
176
- return prepareNextState(state, response);
177
- };
178
- };
179
-
180
- // src/mock.js
181
- var import_undici2 = require("undici");
182
- var sampleRequestBody = {
183
- registry_code: "011803",
184
- child: {
185
- first_name: "Test",
186
- middle_name: "",
187
- Surname: "Testerson",
188
- birth_date: "2024/03/04",
189
- birth_type_code: "1",
190
- gender_code: "2",
191
- place_of_delivery_code: "7",
192
- attendant_at_birth_code: "1",
193
- bith_attendant_full_name: "Helen",
194
- bith_attendant_phone: "0248403076"
195
- },
196
- mother: {
197
- national_id_number: "GHA-000000000-2",
198
- first_name: "fake",
199
- middle_name: "",
200
- maiden_name: "fakerson",
201
- phone: "0248403076",
202
- occupation_code: "29",
203
- age: 25
204
- },
205
- father: {
206
- national_id_number: "",
207
- first_name: "john",
208
- middle_name: "",
209
- Surname: "doe",
210
- phone: "0248403076",
211
- occupation_code: "115",
212
- age: 39
213
- }
214
- };
215
- var birthNotificationResponse = {
216
- birth_certificate_number: "000000-00-2024",
217
- first_name: "Test",
218
- middle_name: "",
219
- Surname: "sample surname",
220
- birth_date: "04 Mar 2024",
221
- national_id_number: "",
222
- place_of_delivery: "MATERNITY HOME",
223
- Health_facility: "",
224
- birth_type: null,
225
- gender: "MALE",
226
- house_number: "",
227
- street_name: "",
228
- district: "",
229
- region: "",
230
- town_or_village: "",
231
- m_first_name: "sample mom",
232
- m_middle_name: "",
233
- m_maiden_name: "sample surname",
234
- m_surname: "",
235
- m_national_id_number: "GHA-000000000-0",
236
- m_nationality: "",
237
- f_first_name: "father fname",
238
- f_middle_name: "",
239
- f_Surname: "father sur",
240
- f_nationality: "",
241
- f_national_id_number: "",
242
- reference_id: "abc123de-1995",
243
- document_number: "1995/000000/XX0000000A1B2C3",
244
- created_at: "05 Mar 2024",
245
- last_updated_at: null,
246
- issuccessful: true,
247
- message: "record reference_id : abc123de-1995 , created successfully",
248
- messagecode: "200"
249
- };
250
- function createServer(url = "http://tracker.chimgh.org") {
251
- const agent = new import_undici2.MockAgent();
252
- agent.disableNetConnect();
253
- const mockPool = agent.get(url);
254
- const sendBirthNotification2 = (req) => {
255
- const body = JSON.parse(req.body);
256
- if (validateRequestBody(body, sampleRequestBody)) {
257
- return {
258
- statusCode: 200,
259
- responseOptions: {
260
- headers: { "Content-Type": "application/json" }
261
- },
262
- data: JSON.stringify(JSON.stringify(birthNotificationResponse))
263
- };
264
- } else {
265
- return {
266
- statusCode: 417,
267
- responseOptions: {
268
- headers: { "Content-Type": "application/json" }
269
- },
270
- data: {
271
- Message: '{"issuccessful":false,"message":"Record failed to save with this error --> Modify the clause to make sure that a column is updated only once. If this statement updates or inserts columns into a view, column aliasing can conceal the duplication in your code.","messagecode":"210"} (Note that this is just a sample error from a mock endpoint.)'
131
+ } = resolvedOptions;
132
+ let attempt = 0;
133
+ const maxAttempts = 2;
134
+ while (attempt < maxAttempts) {
135
+ const auth = await getAccessToken(state);
136
+ state = { ...state, auth };
137
+ try {
138
+ const response = await (0, import_util.request)(method, resolvedPath, {
139
+ baseUrl,
140
+ parseAs: "json",
141
+ body: data,
142
+ query,
143
+ ...otherOptions,
144
+ headers: {
145
+ "Content-Type": "application/json",
146
+ Accept: "application/json",
147
+ ...headers,
148
+ Authorization: `Bearer ${auth.accessToken}`
149
+ }
150
+ });
151
+ (0, import_util.logResponse)(response);
152
+ return prepareNextState(state, response);
153
+ } catch (err) {
154
+ if (attempt < maxAttempts - 1 && err.statusCode === 401) {
155
+ state = { ...state, auth: void 0 };
156
+ attempt++;
157
+ continue;
272
158
  }
273
- };
274
- }
275
- };
276
- mockPool.intercept({ method: "post", path: /api\/notification/ }).reply(sendBirthNotification2).persist();
277
- return {
278
- agent,
279
- request: ({ method, path, data, ...rest }) => {
280
- const opts = {
281
- method,
282
- path,
283
- origin: url,
284
- headers: {},
285
- ...rest
286
- };
287
- if (data) {
288
- opts.body = JSON.stringify(data);
159
+ throw err;
289
160
  }
290
- return mockPool.request(opts);
291
161
  }
292
162
  };
293
163
  }
@@ -302,8 +172,9 @@ function execute(...operations) {
302
172
  };
303
173
  return (state) => {
304
174
  if (!state.configuration.baseUrl) {
305
- const client2 = createServer();
306
- setMockClient(client2);
175
+ throw new Error(
176
+ "Missing configuration.baseUrl. Provide the BDR API base URL (e.g. https://bdr.npontu.com)."
177
+ );
307
178
  }
308
179
  return (0, import_language_common2.execute)(...operations)({ ...initialState, ...state });
309
180
  };
@@ -314,8 +185,11 @@ function get(path, query) {
314
185
  function post(path, data) {
315
186
  return request(path, { data, method: "POST" });
316
187
  }
317
- function sendBirthNotification(data) {
318
- return request("api/notification", {
188
+ function request2(method, path, body, options = {}) {
189
+ return request(path, { method, data: body, ...options });
190
+ }
191
+ function createBirthRecord(data) {
192
+ return request("/api/v1/UserManagementService/integrations/registrations/birth", {
319
193
  method: "POST",
320
194
  data
321
195
  });
@@ -326,6 +200,7 @@ var src_default = Adaptor_exports;
326
200
  // Annotate the CommonJS export names for ESM import in node:
327
201
  0 && (module.exports = {
328
202
  combine,
203
+ createBirthRecord,
329
204
  cursor,
330
205
  dataPath,
331
206
  dataValue,
@@ -341,6 +216,6 @@ var src_default = Adaptor_exports;
341
216
  log,
342
217
  merge,
343
218
  post,
344
- sendBirthNotification,
219
+ request,
345
220
  sourceValue
346
221
  });
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ var __export = (target, all) => {
8
8
  var Adaptor_exports = {};
9
9
  __export(Adaptor_exports, {
10
10
  combine: () => combine,
11
+ createBirthRecord: () => createBirthRecord,
11
12
  cursor: () => cursor,
12
13
  dataPath: () => dataPath,
13
14
  dataValue: () => dataValue,
@@ -23,232 +24,107 @@ __export(Adaptor_exports, {
23
24
  log: () => log,
24
25
  merge: () => merge,
25
26
  post: () => post,
26
- sendBirthNotification: () => sendBirthNotification,
27
+ request: () => request2,
27
28
  sourceValue: () => sourceValue
28
29
  });
29
30
  import { execute as commonExecute } from "@openfn/language-common";
30
31
 
31
- // src/util.js
32
- import undici from "undici";
33
- import nodepath from "path";
32
+ // src/Utils.js
34
33
  import {
35
- throwError,
34
+ request as commonRequest,
36
35
  logResponse,
37
- expandReferences
36
+ expandReferences,
37
+ throwError
38
38
  } from "@openfn/language-common/util";
39
39
  import { composeNextState } from "@openfn/language-common";
40
- var client;
41
- var getClient = (baseUrl) => {
42
- if (baseUrl) {
43
- const url = new URL(baseUrl);
44
- client = new undici.Client(url.origin);
40
+ var TOKEN_PATH = "/api/v1/UserManagementService/integrations/auth/token";
41
+ var getAccessToken = async (state) => {
42
+ var _a;
43
+ const { auth } = state;
44
+ if ((auth == null ? void 0 : auth.accessToken) && auth.expiresAt > Date.now()) {
45
+ return auth;
45
46
  }
46
- return client;
47
- };
48
- var setMockClient = (mockClient) => {
49
- client = mockClient;
50
- };
51
- var validateRequestBody = (request2, sample) => {
52
- const sampleKeys = Object.keys(sample);
53
- const requestKeys = Object.keys(request2);
54
- for (const key of sampleKeys) {
55
- if (!requestKeys.includes(key)) {
56
- console.log("Key missing:", key);
57
- return false;
58
- }
59
- if (typeof sample[key] != typeof request2[key]) {
60
- console.log("Key with wrong value type:", key);
61
- return false;
62
- }
63
- if (typeof sample[key] === "object" && sample[key] !== null) {
64
- if (!validateRequestBody(request2[key], sample[key])) {
65
- console.log("Failed check at:", key);
66
- return false;
67
- }
47
+ const { baseUrl, token } = state.configuration;
48
+ if (!token) {
49
+ throw new Error("Missing configuration.token (long-lived API token)");
50
+ }
51
+ const response = await commonRequest("POST", TOKEN_PATH, {
52
+ baseUrl,
53
+ parseAs: "json",
54
+ headers: {
55
+ "Content-Type": "application/json",
56
+ Accept: "application/json",
57
+ Token: token
68
58
  }
59
+ });
60
+ logResponse(response);
61
+ const { access_token, expires_in } = ((_a = response.body) == null ? void 0 : _a.api_data) ?? {};
62
+ if (!access_token) {
63
+ throwError("BDR_AUTH_ERROR", {
64
+ description: "Malformed token response: missing access_token. The API returned a 200 but the response did not contain a valid token."
65
+ });
66
+ }
67
+ if (!expires_in || typeof expires_in !== "number") {
68
+ throwError("BDR_AUTH_ERROR", {
69
+ description: "Malformed token response: missing or invalid expires_in."
70
+ });
69
71
  }
70
- return true;
72
+ return {
73
+ accessToken: access_token,
74
+ expiresAt: Date.now() + expires_in * 1e3 - 3e4
75
+ };
71
76
  };
72
- var prepareNextState = async (state, response) => {
77
+ var prepareNextState = (state, response) => {
73
78
  const { body, ...responseWithoutBody } = response;
74
- const result = await body.json();
75
- const resultAsJson = JSON.parse(result);
76
- if (!state.references) {
77
- state.references = [];
78
- }
79
- const nextState = {
80
- ...composeNextState(state, resultAsJson),
79
+ return {
80
+ ...composeNextState(state, body),
81
81
  response: responseWithoutBody
82
82
  };
83
- return nextState;
84
83
  };
85
- var request = (path, options) => {
84
+ function request(path, options) {
86
85
  return async (state) => {
87
- const { baseUrl, username, password } = state.configuration;
88
- getClient(baseUrl);
89
- const basePath = baseUrl ? new URL(baseUrl).pathname : "/";
90
- const [resolvedPath, resolvedoptions] = expandReferences(
86
+ const [resolvedPath, resolvedOptions] = expandReferences(
91
87
  state,
92
88
  path,
93
89
  options
94
90
  );
91
+ const { baseUrl } = state.configuration;
95
92
  const {
96
93
  data,
97
- headers = { "content-type": "application/json" },
94
+ headers = {},
98
95
  method = "POST",
99
96
  query,
100
97
  ...otherOptions
101
- } = resolvedoptions;
102
- const safePath = resolvedPath ? nodepath.join(basePath, resolvedPath) : basePath;
103
- const args = {
104
- path: safePath,
105
- data,
106
- headers: {
107
- ...headers
108
- },
109
- method,
110
- query,
111
- ...otherOptions
112
- };
113
- if (data.username || data.password) {
114
- throwError(
115
- "Please don't supply `username` and `password` in your request body. The adaptor will append it automatically."
116
- );
117
- }
118
- if (data) {
119
- args.body = JSON.stringify(
120
- JSON.stringify({
121
- ...data,
122
- username,
123
- password
124
- })
125
- );
126
- args.data = { ...data, username, password };
127
- }
128
- const response = await client.request(args);
129
- if (response.statusCode >= 400) {
130
- throwError("BDR_ERROR", {
131
- code: response.statusCode,
132
- description: response.statusMessage,
133
- body: await response.body.text()
134
- });
135
- }
136
- logResponse(response);
137
- return prepareNextState(state, response);
138
- };
139
- };
140
-
141
- // src/mock.js
142
- import { MockAgent } from "undici";
143
- var sampleRequestBody = {
144
- registry_code: "011803",
145
- child: {
146
- first_name: "Test",
147
- middle_name: "",
148
- Surname: "Testerson",
149
- birth_date: "2024/03/04",
150
- birth_type_code: "1",
151
- gender_code: "2",
152
- place_of_delivery_code: "7",
153
- attendant_at_birth_code: "1",
154
- bith_attendant_full_name: "Helen",
155
- bith_attendant_phone: "0248403076"
156
- },
157
- mother: {
158
- national_id_number: "GHA-000000000-2",
159
- first_name: "fake",
160
- middle_name: "",
161
- maiden_name: "fakerson",
162
- phone: "0248403076",
163
- occupation_code: "29",
164
- age: 25
165
- },
166
- father: {
167
- national_id_number: "",
168
- first_name: "john",
169
- middle_name: "",
170
- Surname: "doe",
171
- phone: "0248403076",
172
- occupation_code: "115",
173
- age: 39
174
- }
175
- };
176
- var birthNotificationResponse = {
177
- birth_certificate_number: "000000-00-2024",
178
- first_name: "Test",
179
- middle_name: "",
180
- Surname: "sample surname",
181
- birth_date: "04 Mar 2024",
182
- national_id_number: "",
183
- place_of_delivery: "MATERNITY HOME",
184
- Health_facility: "",
185
- birth_type: null,
186
- gender: "MALE",
187
- house_number: "",
188
- street_name: "",
189
- district: "",
190
- region: "",
191
- town_or_village: "",
192
- m_first_name: "sample mom",
193
- m_middle_name: "",
194
- m_maiden_name: "sample surname",
195
- m_surname: "",
196
- m_national_id_number: "GHA-000000000-0",
197
- m_nationality: "",
198
- f_first_name: "father fname",
199
- f_middle_name: "",
200
- f_Surname: "father sur",
201
- f_nationality: "",
202
- f_national_id_number: "",
203
- reference_id: "abc123de-1995",
204
- document_number: "1995/000000/XX0000000A1B2C3",
205
- created_at: "05 Mar 2024",
206
- last_updated_at: null,
207
- issuccessful: true,
208
- message: "record reference_id : abc123de-1995 , created successfully",
209
- messagecode: "200"
210
- };
211
- function createServer(url = "http://tracker.chimgh.org") {
212
- const agent = new MockAgent();
213
- agent.disableNetConnect();
214
- const mockPool = agent.get(url);
215
- const sendBirthNotification2 = (req) => {
216
- const body = JSON.parse(req.body);
217
- if (validateRequestBody(body, sampleRequestBody)) {
218
- return {
219
- statusCode: 200,
220
- responseOptions: {
221
- headers: { "Content-Type": "application/json" }
222
- },
223
- data: JSON.stringify(JSON.stringify(birthNotificationResponse))
224
- };
225
- } else {
226
- return {
227
- statusCode: 417,
228
- responseOptions: {
229
- headers: { "Content-Type": "application/json" }
230
- },
231
- data: {
232
- Message: '{"issuccessful":false,"message":"Record failed to save with this error --> Modify the clause to make sure that a column is updated only once. If this statement updates or inserts columns into a view, column aliasing can conceal the duplication in your code.","messagecode":"210"} (Note that this is just a sample error from a mock endpoint.)'
98
+ } = resolvedOptions;
99
+ let attempt = 0;
100
+ const maxAttempts = 2;
101
+ while (attempt < maxAttempts) {
102
+ const auth = await getAccessToken(state);
103
+ state = { ...state, auth };
104
+ try {
105
+ const response = await commonRequest(method, resolvedPath, {
106
+ baseUrl,
107
+ parseAs: "json",
108
+ body: data,
109
+ query,
110
+ ...otherOptions,
111
+ headers: {
112
+ "Content-Type": "application/json",
113
+ Accept: "application/json",
114
+ ...headers,
115
+ Authorization: `Bearer ${auth.accessToken}`
116
+ }
117
+ });
118
+ logResponse(response);
119
+ return prepareNextState(state, response);
120
+ } catch (err) {
121
+ if (attempt < maxAttempts - 1 && err.statusCode === 401) {
122
+ state = { ...state, auth: void 0 };
123
+ attempt++;
124
+ continue;
233
125
  }
234
- };
235
- }
236
- };
237
- mockPool.intercept({ method: "post", path: /api\/notification/ }).reply(sendBirthNotification2).persist();
238
- return {
239
- agent,
240
- request: ({ method, path, data, ...rest }) => {
241
- const opts = {
242
- method,
243
- path,
244
- origin: url,
245
- headers: {},
246
- ...rest
247
- };
248
- if (data) {
249
- opts.body = JSON.stringify(data);
126
+ throw err;
250
127
  }
251
- return mockPool.request(opts);
252
128
  }
253
129
  };
254
130
  }
@@ -278,8 +154,9 @@ function execute(...operations) {
278
154
  };
279
155
  return (state) => {
280
156
  if (!state.configuration.baseUrl) {
281
- const client2 = createServer();
282
- setMockClient(client2);
157
+ throw new Error(
158
+ "Missing configuration.baseUrl. Provide the BDR API base URL (e.g. https://bdr.npontu.com)."
159
+ );
283
160
  }
284
161
  return commonExecute(...operations)({ ...initialState, ...state });
285
162
  };
@@ -290,8 +167,11 @@ function get(path, query) {
290
167
  function post(path, data) {
291
168
  return request(path, { data, method: "POST" });
292
169
  }
293
- function sendBirthNotification(data) {
294
- return request("api/notification", {
170
+ function request2(method, path, body, options = {}) {
171
+ return request(path, { method, data: body, ...options });
172
+ }
173
+ function createBirthRecord(data) {
174
+ return request("/api/v1/UserManagementService/integrations/registrations/birth", {
295
175
  method: "POST",
296
176
  data
297
177
  });
@@ -301,6 +181,7 @@ function sendBirthNotification(data) {
301
181
  var src_default = Adaptor_exports;
302
182
  export {
303
183
  combine,
184
+ createBirthRecord,
304
185
  cursor,
305
186
  dataPath,
306
187
  dataValue,
@@ -317,6 +198,6 @@ export {
317
198
  log,
318
199
  merge,
319
200
  post,
320
- sendBirthNotification,
201
+ request2 as request,
321
202
  sourceValue
322
203
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@openfn/language-ghana-bdr",
3
3
  "label": "Ghana BDR",
4
- "version": "0.2.1",
4
+ "version": "1.0.0",
5
5
  "description": "OpenFn adaptor for Ghana birth-death registry (BDR)",
6
6
  "type": "module",
7
7
  "exports": {
@@ -21,17 +21,14 @@
21
21
  "configuration-schema.json"
22
22
  ],
23
23
  "dependencies": {
24
- "ajv": "^8.20.0",
25
- "undici": "^7.24.7",
26
- "@openfn/language-common": "3.3.3"
24
+ "@openfn/language-common": "3.3.4"
27
25
  },
28
26
  "devDependencies": {
29
27
  "assertion-error": "2.0.0",
30
28
  "chai": "4.3.6",
31
29
  "deep-eql": "4.1.1",
32
30
  "mocha": "^10.7.3",
33
- "rimraf": "3.0.2",
34
- "undici": "^5.29.0"
31
+ "rimraf": "3.0.2"
35
32
  },
36
33
  "repository": {
37
34
  "type": "git",
@@ -41,8 +38,9 @@
41
38
  "main": "dist/index.cjs",
42
39
  "scripts": {
43
40
  "build": "pnpm clean && build-adaptor ghana-bdr",
44
- "test": "mocha --experimental-specifier-resolution=node --no-warnings",
45
- "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings",
41
+ "test": "mocha --experimental-specifier-resolution=node --no-warnings --exclude test/integration.test.js",
42
+ "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings --exclude test/integration.test.js",
43
+ "test:integration": "mocha --experimental-specifier-resolution=node --no-warnings test/integration.test.js",
46
44
  "clean": "rimraf dist types docs",
47
45
  "pack": "pnpm pack --pack-destination ../../dist",
48
46
  "lint": "eslint src"
@@ -6,7 +6,6 @@
6
6
  * @returns {State}
7
7
  */
8
8
  export function execute(...operations: Operation): State;
9
- /**
10
9
  /**
11
10
  * State object
12
11
  * @typedef {Object} HttpState
@@ -40,24 +39,101 @@ export function get(path: string, query: object): Operation;
40
39
  */
41
40
  export function post(path: string, data: object): Operation;
42
41
  /**
43
- * Generate a birth certificate
42
+ * Make a general HTTP request to the BDR API
44
43
  * @example
45
- * sendBirthNotification({
46
- * registry_code: 'abc123',
47
- * child: {},
48
- * mother: {},
49
- * father: {},
44
+ * request("POST", "/api/v1/UserManagementService/integrations/utility", {
45
+ * type: "regions",
46
+ * });
47
+ * @function
48
+ * @public
49
+ * @param {string} method - HTTP method to use
50
+ * @param {string} path - Path to resource
51
+ * @param {object} [body] - Object which will be attached to the request body
52
+ * @param {object} [options] - Optional request options, e.g. query and headers
53
+ * @returns {Operation}
54
+ * @state {HttpState}
55
+ */
56
+ export function request(method: string, path: string, body?: object, options?: object): Operation;
57
+ /**
58
+ * Create a birth record. `child_file_birth_evidence_data` takes an array of
59
+ * base64-encoded data URIs (truncated in the example below).
60
+ * @example <caption>Create a birth record from data on state</caption>
61
+ * createBirthRecord($.data);
62
+ * @example <caption>Create a birth record with a full payload</caption>
63
+ * createBirthRecord({
64
+ * status: "COMPLETE",
65
+ * region_id: 4348,
66
+ * district_id: 338,
67
+ * type_of_birth: "SINGLETON",
68
+ * informant_type: "MOTHER",
69
+ * informant_national_id_type: "GHANA CARD",
70
+ * informant_national_id_number: "34454344",
71
+ * informant_first_name: "David",
72
+ * informant_middle_name: "",
73
+ * informant_last_name: "Godson",
74
+ * informant_region_id: 4348,
75
+ * informant_district_id: 338,
76
+ * informant_residential_address: "Dansoman",
77
+ * informant_phone_number: "2335648498309",
78
+ * child_first_name: "Francis",
79
+ * child_middle_name: "",
80
+ * child_last_name: "Benzoic",
81
+ * child_gender: "MALE",
82
+ * child_dob: "2025-06-26",
83
+ * child_place_of_birth: "HOSPITAL",
84
+ * child_birth_attendant: "MID-WIFE",
85
+ * child_birth_institution: "Ludra Hospital",
86
+ * child_town: "Ashaiman",
87
+ * child_house_no: "H/F286",
88
+ * child_street_name: "Ashaiman Newtown",
89
+ * mother_national_id_type: "GHANA CARD",
90
+ * mother_national_id_number: "32432423433",
91
+ * mother_phone_number: "2335456823893",
92
+ * mother_first_name: "Adwoa",
93
+ * mother_middle_name: "",
94
+ * mother_last_name: "Godson",
95
+ * mother_age: 30,
96
+ * mother_marital_status: "MARRIED",
97
+ * mother_previous_birth_no: 50,
98
+ * mother_occupation: "teacher",
99
+ * mother_educational_level: "DIPLOMA",
100
+ * mother_region_id: 4348,
101
+ * mother_district_id: 338,
102
+ * mother_town: "Accra",
103
+ * mother_religion: "CHRISTIAN",
104
+ * mother_residence: "Tamale",
105
+ * mother_nationality: "GHANA",
106
+ * doubtful_maternity: 0,
107
+ * father_national_id_type: "GHANA CARD",
108
+ * father_national_id_number: "32432423433",
109
+ * father_phone_number: "233548791223",
110
+ * father_first_name: "David",
111
+ * father_middle_name: "",
112
+ * father_last_name: "Godson",
113
+ * father_age: 33,
114
+ * father_marital_status: "MARRIED",
115
+ * father_children_no: 5,
116
+ * father_occupation: "Doctor",
117
+ * father_educational_level: "DIPLOMA",
118
+ * father_region_id: 4348,
119
+ * father_district_id: 338,
120
+ * father_town: "Tema",
121
+ * father_residence: "Tema",
122
+ * father_nationality: "GHANA",
123
+ * father_religion: "CHRISTIAN",
124
+ * doubtful_paternity: 0,
125
+ * child_file_birth_evidence_name: ["Physics.jpg"],
126
+ * child_file_birth_evidence_data: ["data:image/jpeg;base64,/9j/4QAYRXhpZg..."]
50
127
  * })
51
128
  * @function
52
129
  * @public
53
- * @param {object} data - body data to append to the request. JSON will be converted to a string (but a content-type header will not be attached to the request).
130
+ * @param {object} data - body data to append to the request. JSON will be converted to a string.
54
131
  * @returns {Operation}
55
132
  * @state {HttpState}
56
133
  */
57
- export function sendBirthNotification(data: object): Operation;
134
+ export function createBirthRecord(data: object): Operation;
58
135
  /**
59
- * /**
60
- * State object
136
+ * State object
61
137
  */
62
138
  export type HttpState = {
63
139
  /**
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Make an HTTP request.
3
+ * @param {string} path - Path to resource
4
+ * @param {Object} options - Request options (data, headers, method, query, etc.)
5
+ * @returns {Function} A function that takes state and returns a promise of state
6
+ */
7
+ export function request(path: string, options: any): Function;
8
+ export function prepareNextState(state: any, response: any): any;
package/types/mock.d.ts DELETED
@@ -1,10 +0,0 @@
1
- export function createServer(url?: string): {
2
- agent: MockAgent<MockAgent.Options>;
3
- request: ({ method, path, data, ...rest }: {
4
- [x: string]: any;
5
- method: any;
6
- path: any;
7
- data: any;
8
- }) => Promise<import("undici/types/dispatcher.js").default.ResponseData<null>>;
9
- };
10
- import { MockAgent } from "undici/types/index.js";
package/types/util.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export function setMockClient(mockClient: any): void;
2
- export function validateRequestBody(request: any, sample: any): boolean;
3
- export function prepareNextState(state: any, response: any): Promise<any>;
4
- export function request(path: any, options: any): (state: any) => Promise<any>;