Skip to content

Commit

Permalink
Merge pull request #2 from renomureza/use-axios
Browse files Browse the repository at this point in the history
migrate to axios
  • Loading branch information
renomureza authored Oct 6, 2021
2 parents 4615af1 + 5d14947 commit f07bcc3
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 2,681 deletions.
4 changes: 0 additions & 4 deletions .env.example

This file was deleted.

3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
node_modules
.env
coverage
test-dir
package-lock.json
4 changes: 0 additions & 4 deletions .husky/pre-commit

This file was deleted.

19 changes: 12 additions & 7 deletions README-id.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Berikut daftar method yang bisa kita gunakan yang dikembalikan fungsi `rosRest`:

| HTTP | RouterOS | ROS REST | Description |
| ------ | -------- | -------- | ---------------------------------------- |
| GET | print | get | untuk mengambil data |
| GET | print | print | untuk mengambil data |
| PUT | add | add | untuk membuat data baru |
| PATCH | set | set | untuk mempebarui data |
| DELETE | remove | remove | untuk menghapus data |
Expand Down Expand Up @@ -120,26 +120,31 @@ const fetchRouterOS = async () => {
fetchRouterOS();
```

### `get`
Untuk error handling dan response schema, lihat dokumentasi Axios:

- [Error Handling](https://axios-http.com/docs/handling_errors)
- [Response Schema](https://axios-http.com/docs/res_schema)

### `print`

Contoh mengambil semua data IP Address (Winbox: IP > Address):

```js
clientRosRest.get('ip/address');
clientRosRest.print('ip/address');
```

Ambil berdasarkan id, ehter, atau berdasarkan properti yang berisi nilai tertentu:

```js
clientRosRest.get('ip/address/*2');
clientRosRest.get('ip/address/ether1');
clientRosRest.get('ip/address?network=10.155.101.0&dynamic=true');
clientRosRest.print('ip/address/*2');
clientRosRest.print('ip/address/ether1');
clientRosRest.print('ip/address?network=10.155.101.0&dynamic=true');
```

Jika kita hanya memerlukan properti tertentu, gunakan `.proplist`:

```js
clientRosRest.get('ip/address?.proplist=address,disabled');
clientRosRest.print('ip/address?.proplist=address,disabled');
```

### `add`
Expand Down
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Here's a list of the methods we can use that the `rosRest` function returns:

| HTTP | RouterOS | ROS REST | Description |
| ------ | -------- | -------- | ------------------------------------------------------- |
| GET | print | get | To get the records. |
| GET | print | print | To get the records. |
| PUT | add | add | To update a single record. |
| PATCH | set | set | To create a new record. |
| DELETE | remove | remove | To delete a single record. |
Expand Down Expand Up @@ -122,26 +122,31 @@ const fetchRouterOS = async () => {
fetchRouterOS();
```

### `get`
For error handling and response schema, see the Axios documentation:

- [Error Handling](https://axios-http.com/docs/handling_errors)
- [Response Schema](https://axios-http.com/docs/res_schema)

### `print`

Example of retrieving all IP Address data (Winbox: IP > Address):

```js
clientRosRest.get('ip/address');
clientRosRest.print('ip/address');
```

Fetch by id, ether, or by a property containing a specific value:

```js
clientRosRest.get('ip/address/*2');
clientRosRest.get('ip/address/ether1');
clientRosRest.get('ip/address?network=10.155.101.0&dynamic=true');
clientRosRest.print('ip/address/*2');
clientRosRest.print('ip/address/ether1');
clientRosRest.print('ip/address?network=10.155.101.0&dynamic=true');
```

If we only need certain properties, use `.proplist`:

```js
clientRosRest.get('ip/address?.proplist=address,disabled');
clientRosRest.print('ip/address?.proplist=address,disabled');
```

### `add`
Expand Down
10 changes: 0 additions & 10 deletions __test__/config.js

This file was deleted.

55 changes: 0 additions & 55 deletions __test__/index.test.js

This file was deleted.

102 changes: 19 additions & 83 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,90 +1,26 @@
const pathJoin = require('path').join;
const httpsRequest = require('https').request;

const getContentLength = (body = '') => Buffer.byteLength(JSON.stringify(body));

const getBasicAuth = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`;

const getHeaders = ({ user, password, body }) => ({
'Content-Type': 'application/json',
Authorization: getBasicAuth(user, password),
'Content-Length': getContentLength(body),
});

const getPath = (path) => pathJoin('/rest', path);

const getOptionsRequest = ({ routerOS, method, body, path }) => ({
host: routerOS.host,
port: routerOS.port ?? 443,
path: getPath(path),
method,
rejectUnauthorized: routerOS.secure ?? false,
headers: getHeaders({ user: routerOS.user, password: routerOS.password, body }),
});

const response = ({ code, message, data }) => ({ code, message, data });

const responseSuccess = ({ res, data, resolve }) => {
return resolve(
response({
code: res.statusCode,
message: res.statusCode === 204 ? 'successfully removed' : res.statusCode === 201 ? 'added successfully' : null,
data: data ? JSON.parse(data) : null,
})
);
};

const responseError = ({ res, data, reject }) => {
const { detail, message } = JSON.parse(data);
return reject(
response({
code: res.statusCode,
message: detail ?? message,
data: null,
})
);
};

const responseHandler = ({ res, data, resolve, reject }) => {
if ([200, 201, 204].includes(res.statusCode)) {
return responseSuccess({ res, data, resolve });
}
return responseError({ res, reject, data });
};

const makeRequest = ({ routerOS, body, method, path }) => {
return new Promise((resolve, reject) => {
const request = httpsRequest(getOptionsRequest({ routerOS, method, body, path }), (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => responseHandler({ res, data, resolve, reject }));
});

request.on('error', (err) => {
reject(err);
});
request.write(JSON.stringify(body ?? ''));
request.end();
});
};
const { default: axios } = require('axios');
const { Agent } = require('https');

const rosRest = ({ host, port = 443, user, password, secure = false }) => {
const routerOS = {
host,
port,
user,
password,
secure,
};
const instance = axios.create({
httpsAgent: new Agent({ rejectUnauthorized: secure }),
auth: {
username: user,
password,
},
baseURL: `https://${host}:${port}/rest`,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});

return {
get: (path) => makeRequest({ routerOS, method: 'GET', path }),
add: (path, body) => makeRequest({ routerOS, method: 'PUT', path, body }),
set: (path, body) => makeRequest({ routerOS, method: 'PATCH', path, body }),
remove: (path) => makeRequest({ routerOS, method: 'DELETE', path }),
command: (path, body) => makeRequest({ routerOS, method: 'POST', path, body }),
print: (path) => instance.get(path),
add: (path, body) => instance.put(path, body),
set: (path, body) => instance.patch(path, body),
remove: (path, body) => instance.delete(path, body),
command: (path, body) => instance.post(path, body),
};
};

Expand Down
2 changes: 1 addition & 1 deletion jsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"target": "es2020",
"module": "commonJS"
},
"exclude": ["node_modules", ".vscode", "coverage", ".npm", ".yarn", ".husky"]
"exclude": ["node_modules", ".npm", ".yarn"]
}
16 changes: 5 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
{
"name": "ros-rest",
"version": "1.0.1",
"version": "2.0.0",
"main": "index.js",
"author": "R.M Reza",
"license": "MIT",
"scripts": {
"test": "jest -i",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"prepare": "npx husky install"
},
"dependencies": {},
"devDependencies": {
"dotenv": "^10.0.0",
"jest": "^27.2.4"
"scripts": {},
"dependencies": {
"axios": "^0.22.0"
},
"devDependencies": {},
"homepage": "https://github.com/renomureza/ros-rest#readme",
"repository": {
"type": "git",
Expand Down
Loading

0 comments on commit f07bcc3

Please sign in to comment.