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

New template using HTTP utils #460

Merged
merged 5 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
11 changes: 11 additions & 0 deletions packages/common/src/util/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import { Readable } from 'node:stream';

const clients = new Map();

export const makeBasicAuthHeader = (username, password) => {
const buff = Buffer.from(`${username}:${password}`);
const credentials = buff.toString('base64');
return { Authorization: `Basic ${credentials}` };
};

export const logResponse = response => {
const { method, url, statusCode, duration } = response;
console.log(`${method} ${url} - ${statusCode} in ${duration}ms`);
};

const getClient = (baseUrl, options) => {
const { tls, timeout } = options;
if (!clients.has(baseUrl)) {
Expand Down
83 changes: 78 additions & 5 deletions packages/http/ast.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,78 @@
{
"operations": [
{
"name": "request",
"params": [
"method",
"path",
"params",
"callback"
],
"docs": {
"description": "Make a HTTP request",
"tags": [
{
"title": "public",
"description": null,
"type": null
},
{
"title": "example",
"description": "get('/myEndpoint', {\n query: {foo: 'bar', a: 1},\n headers: {'content-type': 'application/json'},\n})"
},
{
"title": "function",
"description": null,
"name": null
},
{
"title": "param",
"description": "The HTTP method to use",
"type": {
"type": "NameExpression",
"name": "string"
},
"name": "method"
},
{
"title": "param",
"description": "Path to resource",
"type": {
"type": "NameExpression",
"name": "string"
},
"name": "path"
},
{
"title": "param",
"description": "Query, Headers and Authentication parameters",
"type": {
"type": "NameExpression",
"name": "RequestOptions"
},
"name": "params"
},
{
"title": "param",
"description": "(Optional) Callback function",
"type": {
"type": "NameExpression",
"name": "function"
},
"name": "callback"
},
{
"title": "returns",
"description": null,
"type": {
"type": "NameExpression",
"name": "Operation"
}
}
]
},
"valid": true
},
{
"name": "get",
"params": [
Expand Down Expand Up @@ -38,7 +111,7 @@
"description": "Query, Headers and Authentication parameters",
"type": {
"type": "NameExpression",
"name": "object"
"name": "RequestOptions"
},
"name": "params"
},
Expand Down Expand Up @@ -101,7 +174,7 @@
"description": "Body, Query, Headers and Authentication parameters",
"type": {
"type": "NameExpression",
"name": "object"
"name": "RequestOptions"
},
"name": "params"
},
Expand Down Expand Up @@ -164,7 +237,7 @@
"description": "Body, Query, Headers and Auth parameters",
"type": {
"type": "NameExpression",
"name": "object"
"name": "RequestOptions"
},
"name": "params"
},
Expand Down Expand Up @@ -227,7 +300,7 @@
"description": "Body, Query, Headers and Auth parameters",
"type": {
"type": "NameExpression",
"name": "object"
"name": "RequestOptions"
},
"name": "params"
},
Expand Down Expand Up @@ -290,7 +363,7 @@
"description": "Body, Query, Headers and Auth parameters",
"type": {
"type": "NameExpression",
"name": "object"
"name": "RequestOptions"
},
"name": "params"
},
Expand Down
16 changes: 5 additions & 11 deletions packages/http/src/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { composeNextState } from '@openfn/language-common';
import {
request as commonRequest,
expandReferences,
logResponse,
makeBasicAuthHeader,
} from '@openfn/language-common/util';

export function addBasicAuth(configuration = {}, headers) {
const { username, password } = configuration;
if (username && password) {
const base64Encode = btoa(`${username}:${password}`);
headers['Authorization'] = `Basic ${base64Encode}`;
Object.assign(headers, makeBasicAuthHeader(username, password));
}
}

Expand All @@ -20,11 +21,6 @@ function encodeFormBody(data) {
return form;
}

export function generateResponseLog(response) {
const { method, url, statusCode, duration } = response;
return `${method} ${url} - ${statusCode} in ${duration}ms`;
}

export function request(method, path, params, callback = s => s) {
return state => {
const [resolvedPath, resolvedParams = {}] = expandReferences(
Expand Down Expand Up @@ -73,8 +69,7 @@ export function request(method, path, params, callback = s => s) {

return commonRequest(method, resolvedPath, options)
.then(response => {
const log = generateResponseLog(response);
console.log(log);
logResponse(response);

return {
...composeNextState(state, response.body),
Expand All @@ -83,8 +78,7 @@ export function request(method, path, params, callback = s => s) {
})
.then(callback)
.catch(err => {
const log = generateResponseLog(err);
console.log(log);
logResponse(err);

throw err;
});
Expand Down
2 changes: 1 addition & 1 deletion packages/template/ast.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
},
{
"title": "param",
"description": "The data to create the new resource",
"description": "The data to create the new resource from",
"type": {
"type": "NameExpression",
"name": "object"
Expand Down
56 changes: 33 additions & 23 deletions packages/template/src/Adaptor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import {
execute as commonExecute,
composeNextState,
} from '@openfn/language-common';
import { expandReferences } from '@openfn/language-common/util'
import { expandReferences } from '@openfn/language-common/util';
import { request } from './Utils';

// TODO You can override the execute function to run code at the start
// and end of job execution. This is useful for initialising and destroying
// client objects. In this example we need it to create the references array.
/**
* Execute a sequence of operations.
* Wraps `language-common/execute` to make working with this API easier.
Expand Down Expand Up @@ -32,45 +35,52 @@ export function execute(...operations) {
};
}

// TODO this is example Opeartions which might create a resource on
// on a fictional service. It demonstrates best practice for how
// Operations should be written
/**
* Create some resource in some system
* @public
* @example
* create("patient", {"name": "Bukayo"})
* @function
* @param {string} resource - The type of entity that will be created
* @param {object} data - The data to create the new resource
* @param {object} data - The data to create the new resource from
* @param {function} callback - An optional callback function
* @returns {Operation}
*/
export function create(resource, data, callback) {
return state => {
const [resolvedResource, resolvedData] = expandReferences(state, resource, data);

const { baseUrl, username, password } = state.configuration;
export function create(resource, data, callback = s => s) {
return async state => {
// Parameters like resource and data might be passed as functions, which
// allow us to lazily evaluate state references
// The expand function will either return the provided values back to us,
// or evaluate them first
const [resolvedResource, resolvedData] = expandReferences(
state,
resource,
data
);

const url = `${baseUrl}/api/${resolvedResource}`;
const auth = { username, password };
// Make the request to the service
// See src/Utils.js for the request implementation
const response = await request(
state,
'POST',
resolvedResource,
resolvedData
);

const options = {
auth,
body: resolvedData,
method: 'POST',
// Write the result to state.data, update the references array, and save response metadata
const nextState = {
...composeNextState(state, response.body),
response,
};

return request(url, options).then(response => {
const nextState = {
...composeNextState(state, response.data),
response,
};
if (callback) return callback(nextState);
return nextState;
});
// Invoke the callback (if passed) before returning
return callback(nextState);
};
}

export { request } from './Utils';

// TODO: Decide which functions to publish from @openfn/language-common
export {
dataPath,
Expand Down
74 changes: 44 additions & 30 deletions packages/template/src/Utils.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,47 @@
// TODO: Determine how to authenticate for the target API
function makeAuthHeader(auth) {
const { username, password } = auth;
const buff = Buffer.from(`${username}:${password}`);
const credentials = buff.toString('base64');
return { Authorization: `Basic ${credentials}` };
}

export async function request(url, options) {
const { auth } = options;
delete options.auth;

const response = await fetch(url, {
...options,
/**
* If you have any helper functions which are NOT operations,
* you should add them here
*/

import {
request as commonRequest,
makeBasicAuthHeader,
} from '@openfn/language-common/util';

// This helper function will call out to the backend service
// And add authorisation headers
export const request = (state, method, path, data) => {
// TODO This example adds basic auth from config data
// you may need to support other auth strategies
const { baseUrl, username, password } = state.configuration;
const headers = makeBasicAuthHeader(username, password);

// TODO You can define custom error messages here
// The request function will throw if it receives
// an error code (<=400), terminating the workflow
const errors = {
404: 'Page not found',
};

const options = {
// Append data to the request body
body: data,

// You can dd extra headers here if yout want to
headers: {
...headers,
'content-type': 'application/json',
...makeAuthHeader(auth),
},
});

// TODO: Handle errors based on the behavior of the target API
if (response.status === 404) {
throw new Error('Page not found');
} else if (response.status === 500) {
throw new Error('Server error');
} else if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

// TODO: Extract data from response based on the target API
const data = await response.json();
return data;
}

// Force the response to be parsed as JSON
parseAs: 'json',

// Include the error map
errors,
};

// Build the url base on the baseUrl in config and the path provided
const url = `${baseUrl}/api/${path}`;
// Make the actual request
return commonRequest(method, url, options);
};
Loading