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 how to page on updating hof projects to use axios #23

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all 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
161 changes: 161 additions & 0 deletions wiki/Wiki_How_Tos/3.axios-updates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
---
title: Replace Request with Axios
---

This is a basic documentation page to help developer to use an updated version of the HOF framework to implement the replacement of the request.js module with axios. Both modules help developers make HTTP requests for NodeJS applications where a successful request returns a response and a failed request returns an error. The request module is now deprecated and has been replaced with axios in the HOF framework.


<br>

```toc
# This code block gets replaced with the Table Of Contents
```


## Package.json updates

- Specify package to use `hof@~21.0.0`
- Run `yarn install`

- Make dev use the .env file (command varies on projects)
```js:title=basic-dev-cmd.js
"dev": "NODE_ENV=development hof-build watch --env"
```

## Run the application

The Hof model uses axios so services do not need to use a standalone axios module. You can require the hof model in your behaviours and models, and access axios using the hof model's request function.

```
const Model = require('hof').model;
```

To access response statuscodes using axios you will need to change the request module's `statusCode` property to `status`.

`response.statusCode`
becomes
`response.status`

To access response data using axios you will need to change the request module's `body` property to `data`.
`response.body`
becomes
`response.data`

## Breaking changes
Some behaviours and models will need to be refactored in order to use the updated hof model that uses axios.

### File Uploads

#### Auth model

Use an async/await function to set up the auth model. Note that the `form` property previously used by request has changed to the `data` propertyin the tokenReq object when using axios. To access the access token `response.data.access_token` must be used instead of `response.body.access_token`.

```js:title=models > auth.js
'use strict';

const Model = require('hof').model;
const config = require('../../../config');

module.exports = class AuthToken extends Model {
async auth() {
/* eslint-disable no-console */
try {
if (!config.keycloak.token) {
console.error('keycloak token url is not defined');
return {
bearer: 'abc123'
};
}
const tokenReq = {
url: config.keycloak.token,
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
username: config.keycloak.username,
password: config.keycloak.password,
grant_type: 'password',
client_id: config.keycloak.clientId,
client_secret: config.keycloak.secret
},
method: 'POST'
};
const response = await this._request(tokenReq);
return { bearer: response.data.access_token };
} catch (error) {
console.error('Error in auth method:', error);
throw error;
}
}
};

```

#### File upload model
Axios requires the FormData object to upload files.
```js:title=models > file-upload.js
const FormData = require('form-data');
```
Set the file data to the form data object and post the request using async/await.

```js:title=models > file-upload.js
async save() {
try {
const attributes = {
url: config.upload.hostname
};
const reqConf = url.parse(this.url(attributes));

const formData = new FormData();
formData.append('document', this.get('data'), {
filename: this.get('name'),
contentType: this.get('mimetype')
});
reqConf.data = formData;
reqConf.method = 'POST';
reqConf.headers = {
...formData.getHeaders()
};

const response = await this.request(reqConf);

return response.data;
} catch (err) {
console.error('Error in save method:', err);
throw err;
}
}
```
### HTML to PDF Converter
#### Additions to PDF model
Add the rejectUnauthorized and responseType attributes to the requestConfig function
```js:title=models > pdf.js
requestConfig(options) {
const settings = super.requestConfig(options);
settings.encoding = null;
settings.rejectUnauthorized = false;
settings.responseType = 'arraybuffer';
return settings;
}
```

### Save and Return
#### Save Form session and Resume Form session
Create a new instance of the hof model. Then set the url, method and data (if required) parameters to a params object and pass it as an argument to the hof model's request function.

```js:title=behaviours > save-form-session.js
const Model = require('hof').model;
const config = require('../../../config');
const _ = require('lodash');
...
req.log('info', `Saving Form Session: ${req.sessionModel.get('id')}`);

const id = req.sessionModel.get('id');
const model = new Model();
const params = {
url: patchUrl(id),
data: { session },
method: 'PATCH'
};
return model._request(params, {
...
});
```