Skip to content
This repository has been archived by the owner on Oct 21, 2022. It is now read-only.

Commit

Permalink
standardize and remove custom URL param builder
Browse files Browse the repository at this point in the history
  • Loading branch information
taylordowns2000 committed Dec 22, 2021
1 parent 62b4e24 commit 8f1bbe8
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 67 deletions.
9 changes: 5 additions & 4 deletions lib/Adaptor.js
Expand Up @@ -149,6 +149,7 @@ function configMigrationHelper(state) {
_axios.default.interceptors.response.use(function (response) {
var _response$headers$con, _response;

console.log(response);
const contentType = (_response$headers$con = response.headers['content-type']) === null || _response$headers$con === void 0 ? void 0 : _response$headers$con.split(';')[0];
const acceptHeaders = response.config.headers['Accept'].split(';')[0].split(',');

Expand Down Expand Up @@ -311,7 +312,7 @@ function create(resourceType, data, options, callback) {
return (0, _Client.request)(configuration, {
method: 'post',
url: (0, _Utils.generateUrl)(configuration, options, resourceType),
params: params && (0, _Utils.buildUrlParams)(params),
params,
data: (0, _Utils.nestArray)(data, resourceType),
...requestConfig
}).then(result => {
Expand Down Expand Up @@ -473,7 +474,7 @@ function update(resourceType, path, data, options, callback) {
return (0, _Client.request)(configuration, {
method: 'put',
url: `${(0, _Utils.generateUrl)(configuration, options, resourceType)}/${path}`,
params: params && (0, _Utils.buildUrlParams)(params),
params,
data,
...requestConfig
}).then(result => {
Expand Down Expand Up @@ -526,9 +527,9 @@ function get(resourceType, filters, options, callback) {
return (0, _Client.request)(configuration, {
method: 'get',
url: (0, _Utils.generateUrl)(configuration, options, resourceType),
params: (0, _Utils.buildUrlParams)({ ...filters,
params: { ...filters,
...params
}),
},
responseType: 'json',
...requestConfig
}).then(result => {
Expand Down
27 changes: 12 additions & 15 deletions lib/Utils.js
Expand Up @@ -8,7 +8,6 @@ exports.handleResponse = handleResponse;
exports.prettyJson = prettyJson;
exports.nestArray = nestArray;
exports.generateUrl = generateUrl;
exports.buildUrlParams = buildUrlParams;
exports.Log = exports.CONTENT_TYPES = void 0;

var _languageCommon = require("@openfn/language-common");
Expand Down Expand Up @@ -76,17 +75,15 @@ function generateUrl(configuration, options, resourceType) {
const apiMessage = apiVersion ? `Using DHIS2 api version ${apiVersion}` : 'Using latest available version of the DHIS2 api on this server.';
console.log(apiMessage);
return buildUrl(urlString, hostUrl, apiVersion);
}

function buildUrlParams(params) {
const filters = params === null || params === void 0 ? void 0 : params.filters;
const dimensions = params === null || params === void 0 ? void 0 : params.dimensions; // We remove filters and dimensions before building standard search params.

params === null || params === void 0 ? true : delete params.filters;
params === null || params === void 0 ? true : delete params.dimensions;
const urlParams = new URLSearchParams(params); // Then we re-apply the filters and dimensions in this dhis2-specific way.

filters === null || filters === void 0 ? void 0 : filters.map(f => urlParams.append('filter', f));
dimensions === null || dimensions === void 0 ? void 0 : dimensions.map(d => urlParams.append('dimension', d));
return urlParams;
}
} // export function buildUrlParams(params) {
// const filters = params?.filters;
// const dimensions = params?.dimensions;
// // We remove filters and dimensions before building standard search params.
// delete params?.filters;
// delete params?.dimensions;
// const urlParams = new URLSearchParams(params);
// // Then we re-apply the filters and dimensions in this dhis2-specific way.
// filters?.map(f => urlParams.append('filter', f));
// dimensions?.map(d => urlParams.append('dimension', d));
// return urlParams;
// }
19 changes: 9 additions & 10 deletions src/Adaptor.js
Expand Up @@ -8,7 +8,6 @@ import {
import { indexOf } from 'lodash';
import {
buildUrl,
buildUrlParams,
CONTENT_TYPES,
generateUrl,
handleResponse,
Expand Down Expand Up @@ -125,7 +124,7 @@ axios.interceptors.response.use(
* @function
* @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`, `programs`, `events`, ...
* @param {Object} data - Data that will be used to create a given instance of resource. To create a single instance of a resource, `data` must be a javascript object, and to create multiple instances of a resources, `data` must be an array of javascript objects.
* @param {Object} [options] - Optional `options` to define URL parameters (E.g. `filters`, `dimensions` and `import parameters`), axios configurations (E.g. `auth`) and DHIS 2 api version to use.
* @param {Object} [options] - Optional `options` to define URL parameters (E.g. `filter`, `dimension` and other import parameters), request config (E.g. `auth`) and the DHIS2 apiVersion.
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>a program</caption>
Expand Down Expand Up @@ -233,7 +232,7 @@ export function create(resourceType, data, options, callback) {
return request(configuration, {
method: 'post',
url: generateUrl(configuration, options, resourceType),
params: params && buildUrlParams(params),
params,
data: nestArray(data, resourceType),
...requestConfig,
}).then(result => {
Expand All @@ -251,7 +250,7 @@ export function create(resourceType, data, options, callback) {
* @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
* @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
* @param {Object} data - Data to update. It requires to send `all required fields` or the `full body`. If you want `partial updates`, use `patch` operation.
* @param {Object} [options] - Optional `options` to define URL parameters (E.g. `filters`, `dimensions` and `import parameters`), axios configurations (E.g. `auth`) and DHIS 2 api version to use.
* @param {Object} [options] - Optional `options` to define URL parameters (E.g. `filter`, `dimension` and other import parameters), request config (E.g. `auth`) and the DHIS2 apiVersion.
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>a program</caption>
Expand Down Expand Up @@ -391,7 +390,7 @@ export function update(resourceType, path, data, options, callback) {
return request(configuration, {
method: 'put',
url: `${generateUrl(configuration, options, resourceType)}/${path}`,
params: params && buildUrlParams(params),
params,
data,
...requestConfig,
}).then(result => {
Expand All @@ -407,7 +406,7 @@ export function update(resourceType, path, data, options, callback) {
* @public
* @function
* @param {string} resourceType - The type of resource to get(use its `plural` name). E.g. `dataElements`, `trackedEntityInstances`,`organisationUnits`, etc.
* @param {Object} filters - Filters to limit what resources are retrieved.
* @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 beyond filters, request configuration (e.g. `auth`) and DHIS2 api version to use.
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation} state
Expand All @@ -423,15 +422,15 @@ export function update(resourceType, path, data, options, callback) {
* @example <caption>a single tracked entity instance by a unique external ID</caption>
* get('trackedEntityInstances', {
* ou: 'DiszpKrYNg8',
* filters: ['flGbXLXCrEo:Eq:124'],
* filter: ['flGbXLXCrEo:Eq:124', 'w75KJ2mc4zz:Eq:John'],
* });
*/
export function get(resourceType, filters, options, callback) {
export function get(resourceType, query, options, callback) {
return state => {
console.log(`Preparing get operation...`);

resourceType = expandReferences(resourceType)(state);
filters = expandReferences(filters)(state);
query = expandReferences(query)(state);
options = expandReferences(options)(state);

const { params, requestConfig } = options || {};
Expand All @@ -440,7 +439,7 @@ export function get(resourceType, filters, options, callback) {
return request(configuration, {
method: 'get',
url: generateUrl(configuration, options, resourceType),
params: buildUrlParams({ ...filters, ...params }),
params: { ...query, ...params },
responseType: 'json',
...requestConfig,
}).then(result => {
Expand Down
17 changes: 0 additions & 17 deletions src/Utils.js
Expand Up @@ -59,20 +59,3 @@ export function generateUrl(configuration, options, resourceType) {

return buildUrl(urlString, hostUrl, apiVersion);
}

export function buildUrlParams(params) {
const filters = params?.filters;
const dimensions = params?.dimensions;

// We remove filters and dimensions before building standard search params.
delete params?.filters;
delete params?.dimensions;

const urlParams = new URLSearchParams(params);

// Then we re-apply the filters and dimensions in this dhis2-specific way.
filters?.map(f => urlParams.append('filter', f));
dimensions?.map(d => urlParams.append('dimension', d));

return urlParams;
}
23 changes: 3 additions & 20 deletions test/index.js
@@ -1,7 +1,7 @@
import { expect } from 'chai';
import { execute, create, update, get, upsert } from '../lib/Adaptor';
import { dataValue } from '@openfn/language-common';
import { buildUrl, buildUrlParams, generateUrl, nestArray } from '../lib/Utils';
import { buildUrl, generateUrl, nestArray } from '../lib/Utils';
import nock from 'nock';

const testServer = nock('https://play.dhis2.org/2.36.4');
Expand Down Expand Up @@ -327,38 +327,21 @@ describe('URL builders', () => {
const options = {
...fixture.options,
apiVersion: 33,
params: { filters: ['a:eq:b', 'c:ge:d'] },
params: { filter: ['a:eq:b', 'c:ge:d'] },
};

const finalURL = generateUrl(
fixture.configuration,
options,
fixture.resourceType
);

const expectedURL = 'https://play.dhis2.org/2.36.4/api/33/dataValueSets';

expect(finalURL).to.eq(expectedURL);
done();
});
});

describe('buildURLParams', () => {
it('should handle special filter and dimensions params and build the rest per usual', () => {
const params = {
dryRun: true,
filters: ['sex:eq:male', 'origin:eq:senegal'],
someNonesense: 'other',
dimensions: ['dx:fbfJHSPpUQD', 'ou:O6uvpzGd5pu;lc3eMKXaEfw'],
};

const finalParams = buildUrlParams(params).toString();

const expected =
'dryRun=true&someNonesense=other&filter=sex%3Aeq%3Amale&filter=origin%3Aeq%3Asenegal&dimension=dx%3AfbfJHSPpUQD&dimension=ou%3AO6uvpzGd5pu%3Blc3eMKXaEfw';

expect(finalParams).to.eq(expected);
});
});
});

describe('nestArray', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/integration.js
Expand Up @@ -263,7 +263,7 @@ describe('get', () => {
data: {},
};

it('should get dataValueSets matching the filters specified', async () => {
it('should get dataValueSets matching the query specified', async () => {
const finalState = await execute(
get('dataValueSets', {
dataSet: 'pBOMPrpg1QX',
Expand Down

0 comments on commit 8f1bbe8

Please sign in to comment.