Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add asBase64 option in dhis2 get() function #939

Merged
merged 9 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stale-insects-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@openfn/language-dhis2': minor
---

Add `asBase64` option in dhis2 `get()` function
39 changes: 38 additions & 1 deletion packages/dhis2/ast.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,43 @@
},
"name": "options"
},
{
"title": "param",
"description": "The parameters for the request.",
"type": {
"type": "OptionalType",
"expression": {
"type": "NameExpression",
"name": "Object"
}
},
"name": "options.params"
},
{
"title": "param",
"description": "The configuration for the request, including headers, etc.",
"type": {
"type": "OptionalType",
"expression": {
"type": "NameExpression",
"name": "Object"
}
},
"name": "options.requestConfig"
},
{
"title": "param",
"description": "Optional flag to indicate if the response should be returned as a Base64 encoded string.",
"type": {
"type": "OptionalType",
"expression": {
"type": "NameExpression",
"name": "boolean"
}
},
"name": "options.asBase64",
"default": "false"
},
{
"title": "param",
"description": "Optional callback to handle the response",
Expand Down Expand Up @@ -382,7 +419,7 @@
}
]
},
"valid": true
"valid": false
},
{
"name": "post",
Expand Down
24 changes: 17 additions & 7 deletions packages/dhis2/src/Adaptor.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import { execute as commonExecute } from '@openfn/language-common';
import { expandReferences } from '@openfn/language-common/util';
import { expandReferences, encode } from '@openfn/language-common/util';
import _ from 'lodash';
const { indexOf } = _;
import {
Expand Down Expand Up @@ -79,7 +79,10 @@ axios.interceptors.response.use(
.split(';')[0]
.split(',');

if (response.config.method === 'get') {
if (
response.config.method === 'get' &&
response.config.responseType != 'arraybuffer'
) {
if (indexOf(acceptHeaders, contentType) === -1) {
const newError = {
status: 404,
Expand Down Expand Up @@ -475,6 +478,9 @@ export function update(
* @param {string} resourceType - The type of resource to get(use its `plural` name). E.g. `dataElements`, `tracker/trackedEntities`,`organisationUnits`, etc.
* @param {Object} query - A query object that will limit what resources are retrieved when converted into request params.
* @param {Object} [options] - Optional `options` to define URL parameters via params beyond filters, request configuration (e.g. `auth`) and DHIS2 api version to use.
* @param {Object} [options.params] - The parameters for the request.
* @param {Object} [options.requestConfig] - The configuration for the request, including headers, etc.
* @param {boolean} [options.asBase64=false] - Optional flag to indicate if the response should be returned as a Base64 encoded string.
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation} state
* @example <caption>Get all data values for the 'pBOMPrpg1QX' dataset</caption>
Expand All @@ -497,25 +503,29 @@ export function update(
* trackedEntity:['F8yKM85NbxW'],
* });
*/
export function get(resourceType, query, options = {}, callback = false) {
export function get(resourceType, query, options = {}, callback = s => s) {
return state => {
console.log('Preparing get operation...');

const [resolvedResourceType, resolvedQuery, resolvedOptions] =
expandReferences(state, resourceType, query, options);

const { params, requestConfig } = resolvedOptions;
const { params, requestConfig, asBase64 = false } = resolvedOptions;
const { configuration } = state;

return request(configuration, {
method: 'get',
url: generateUrl(configuration, resolvedOptions, resolvedResourceType),
params: { ...resolvedQuery, ...params },
responseType: 'json',
params: {
...resolvedQuery,
...params,
},
responseType: asBase64 ? 'arraybuffer' : 'json',
...requestConfig,
}).then(result => {
console.log(`Retrieved ${resolvedResourceType}`);
return handleResponse(result, state, callback);
const response = asBase64 ? { data: encode(result.data) } : result;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sent me on a bit of a rabbit hole. I think it will be really healthy to rebsae dhis2 on unidic and make it much more standardised

return handleResponse(response, state, callback);
});
};
}
Expand Down
33 changes: 16 additions & 17 deletions packages/dhis2/src/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,32 @@ export function request({ username, password, pat }, axiosRequest) {
const { method, url, params } = axiosRequest;

console.log(`Sending ${method} request to ${url}`);
if (params) console.log(` with params:`, params);
if (params) console.log(`with params: `, params);

// NOTE: We don't follow redirects for unsafe methods: https://github.com/axios/axios/issues/2460
const safeRedirect = ['get', 'head', 'options', 'trace'].includes(
method.toLowerCase()
);

// Declare auth property and headers dynamically
const headers = { 'Content-Type': 'application/json'}
const headers = {
'Content-Type': 'application/json',
};
let auth;

if(pat){
headers.Authorization = `ApiToken ${pat}`
if (pat) {
headers.Authorization = `ApiToken ${pat}`;
} else {
auth = { username, password }
auth = { username, password };
}


return axios(
{
headers,
responseType: 'json',
auth,
maxRedirects: safeRedirect ? 5 : 0,
paramsSerializer: params => Qs.stringify(params, { arrayFormat: 'repeat' }),
// Note that providing headers or auth in the request object will overwrite.
...axiosRequest,
}
);
return axios({
headers,
responseType: 'json',
auth,
maxRedirects: safeRedirect ? 5 : 0,
paramsSerializer: params => Qs.stringify(params, { arrayFormat: 'repeat' }),
// Note that providing headers or auth in the request object will overwrite.
...axiosRequest,
});
}
Loading