Skip to content

Commit

Permalink
feat(Axios): Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
cblanc committed Jan 22, 2020
0 parents commit 784baf3
Show file tree
Hide file tree
Showing 20 changed files with 11,863 additions and 0 deletions.
50 changes: 50 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
default_steps: &default_steps
working_directory: ~/repo
steps:
- checkout
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package-lock.json" }}
- run: npm install
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package-lock.json" }}
- run: npm test
- run: npm run coverage

version: 2
jobs:
node_8:
<<: *default_steps
docker:
- image: circleci/node:8
node_10:
<<: *default_steps
docker:
- image: circleci/node:10
node_12:
<<: *default_steps
docker:
- image: circleci/node:12

workflows:
version: 2
push:
jobs:
- node_8
- node_10
- node_12
scheduled:
jobs:
- node_8
- node_10
- node_12
triggers:
- schedule:
cron: "8 8 * * 1-5"
filters:
branches:
only:
- master
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[Makefile]
indent_style = tab
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
extends: "@cablanchard",
};
64 changes: 64 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# dotenv environment variables file
.env

dist

.cache

.DS_Store

docs/
Empty file added CHANGELOG.md
Empty file.
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2018 Christopher Blanchard, Michael Blanchard

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<h1 align="center">
<img src="https://img.ideal-postcodes.co.uk/Ideal%20Postcodes%20Node%20Logo@3x.png" alt="Ideal Postcodes Node.js">
</h1>

> Axios client for api.ideal-postcodes.co.uk
[![CircleCI](https://circleci.com/gh/ideal-postcodes/core-axios/tree/master.svg?style=svg)](https://circleci.com/gh/ideal-postcodes/core-axios/tree/master)
[![codecov](https://codecov.io/gh/ideal-postcodes/core-axios/branch/master/graph/badge.svg)](https://codecov.io/gh/ideal-postcodes/core-axios)
[![Dependency Status](https://david-dm.org/ideal-postcodes/core-axios//david-dm.org/ideal-postcodes/core-axios)
[![npm version](https://badge.fury.io/js/%40ideal-postcodes%2Fcore-axios//www.npmjs.com/package/@ideal-postcodes/core-axios)
[![install size](https://packagephobia.now.sh/badge?p=@ideal-postcodes/core-axios)](https://packagephobia.now.sh/result?p=@ideal-postcodes/core-axios)

`@ideal-postcodes/core-axios` is the Axios client for api.ideal-postcodes.co.uk

Our JavaScript client implements a common interface defined at [@ideal-postcodes/core-interface](https://github.com/ideal-postcodes/core-interface).

High level client documentation can be found at [core-interface](https://github.com/ideal-postcodes/core-interface/blob/master/README.md).

In depth client documentation can be found at [core-interface.ideal-postcodes.dev](https://core-interface.ideal-postcodes.dev).

## Links

- [Configuration & Usage](#configuration--usage)
- [Quickstart](#quickstart)
- [Client Documentation](https://github.com/ideal-postcodes/core-interface/blob/master/README.md)
- [In Depth Client Documentation](https://core-interface.ideal-postcodes.dev/#documentation)
- [npm Module](https://www.npmjs.com/package/@ideal-postcodes/core-axios)
- [GitHub Repository](https://github.com/ideal-postcodes/core-axios)

## Other JavaScript Clients

- [Node.js Client Repository](https://github.com/ideal-postcodes/core-node)
- [Browser Client Repository](https://github.com/ideal-postcodes/core-browser)
- [Bundled Browser Client Repository](https://github.com/ideal-postcodes/core-browser-bundled)

## Documentation

### Configuration & Usage

- [Install](#install)
- [Instantiate](#instantiate) and [Use](#use) client
- [Catch Errors](#catch-errors)
- [Configure Agent](#configure-http-agent)
- [Proxy HTTP Requests](#proxy-requests)

#### Install

```bash
npm install @ideal-postcodes/core-axios
```

#### Instantiate

```javascript
const { Client } = require("@ideal-postcodes/core-axios");

// or, if applicable,
import { Client } from "@ideal-postcodes/core-axios"

const client = new Client({ api_key: "iddqd" });
```

[Configuration options](https://core-interface.ideal-postcodes.dev/interfaces/config.html)

#### Use

```javascript
const addresses = await client.lookupPostcode({ postcode: "SW1A2AA" });
```

#### Catch Errors

```javascript
const { IdpcRequestFailedError } = Client.errors;

try {
await client.lookupAddress({ query: "10 downing street" });
} catch (error) {
if (error instanceof IdpcRequestFailedError) {
// IdpcRequestFailedError indicates a 402 response code
// Possibly the key balance has been depleted
}
}
```

## Test

```bash
npm test
```

## Licence

MIT
124 changes: 124 additions & 0 deletions lib/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import Axios from "axios";
import { AxiosResponse, AxiosInstance } from "axios";
import {
Agent as IAgent,
HttpRequest,
HttpResponse,
errors,
} from "@ideal-postcodes/core-interface";

const {
/**
* Ideal Postcodes base error class implemented in [core-interface](https://core-interface.ideal-postcodes.dev/classes/idealpostcodeserror.html)
*/
IdealPostcodesError,
} = errors;

// @hidden
interface GotHeaders {
[key: string]: string | string[] | undefined;
}

/**
* @hidden
*/
interface ToHeader {
(gotHeaders: GotHeaders): Record<string, string>;
}

/**
* Converts a Got header object to one that can be used by the client
*
* @hidden
*/
export const toHeader: ToHeader = gotHeaders =>
Object.keys(gotHeaders).reduce<Record<string, string>>((headers, key) => {
const val = gotHeaders[key];
if (typeof val === "string") {
headers[key] = val;
} else if (Array.isArray(val)) {
headers[key] = val.join(",");
}
return headers;
}, {});

/**
* Adapts got responses to a format consumable by core-interface
*
* @hidden
*/
const toHttpResponse = (
httpRequest: HttpRequest,
response: AxiosResponse<object>
): HttpResponse => ({
httpRequest,
body: response.data,
httpStatus: response.status || 0,
header: toHeader(response.headers),
metadata: { response },
});

/**
* Catch non-response errors (e.g. network failure, DNS failure, timeout)
* wrap in our Error class and return
*
* @hidden
*/
const handleError = (error: Error): Promise<never> => {
const idpcError = new IdealPostcodesError({
message: `[${error.name}] ${error.message}`,
httpStatus: 0,
metadata: { axios: error },
});
return Promise.reject(idpcError);
};

// Don't throw errors for any HTTP status code
// Allow core-interface to absorb these and emit own errors
const validateStatus = () => true;

/**
* Agent
*
* @hidden
*/
export class Agent implements IAgent {
public Axios: AxiosInstance;

constructor() {
this.Axios = Axios.create({ validateStatus });
}

private requestWithBody(httpRequest: HttpRequest): Promise<HttpResponse> {
const { body, method, timeout, url, header, query } = httpRequest;
return this.Axios.request({
url,
method,
headers: header,
params: query,
data: body,
timeout,
})
.then(response => toHttpResponse(httpRequest, response))
.catch(handleError);
}

private request(httpRequest: HttpRequest): Promise<HttpResponse> {
const { method, timeout, url, header, query } = httpRequest;
return this.Axios.request({
url,
method,
headers: header,
params: query,
timeout,
})
.then(response => toHttpResponse(httpRequest, response))
.catch(handleError);
}

public http(httpRequest: HttpRequest): Promise<HttpResponse> {
if (httpRequest.body !== undefined)
return this.requestWithBody(httpRequest);
return this.request(httpRequest);
}
}

0 comments on commit 784baf3

Please sign in to comment.