Giter VIP home page Giter VIP logo

opencage-api-client's Introduction

opencage-api-client

Version Downloads GitHub license Maintained

This repository is an OpenCage Geocoding API client for JavaScript and node.

Continuous integration

CircleCI (all branches) codecov Maintainability Reviewed by Hound

Security

Source Scores
Meterian security status stability status
FOSSA FOSSA Status
Snyk Known Vulnerabilities

Tutorial

You can find a comprehensive tutorial for using this module on the OpenCage site.

πŸ”§ Getting started

Signup for a free-trial API Key.

node

The library uses dotenv on node runtime to configure OpenCage Geocoding API key. But using key as an input parameter is always a possiblity.

First install the library with npm or yarn:

$ npm i --save opencage-api-client

or

$ yarn add opencage-api-client

or

$ pnpm add opencage-api-client

Create a .env file with:

OPENCAGE_API_KEY=YOUR-OPENCAGE_DATA_API_KEY

Here is an example:

const opencage = require('opencage-api-client');

opencage
  .geocode({ q: 'lyon' })
  .then((data) => {
    console.log(JSON.stringify(data));
  })
  .catch((error) => {
    console.log('error', error.message);
  });

browser

The browser version is built over the node one, obviously without the dotenv feature.

The library is available with unkpg CDN : https://unpkg.com/opencage-api-client

1- include the library:

<!-- latest version -->
<script src="https://unpkg.com/opencage-api-client"></script>
<!-- specific version -->
<script src="https://unpkg.com/[email protected]/dist/opencage-api.min.js"></script>

2- use it

opencage
  .geocode({ q: 'lyon', key: 'YOUR-API-KEY' })
  .then((data) => {
    console.log(JSON.stringify(data));
  })
  .catch((error) => {
    console.log('Error caught:', error.message);
  });

3- others Examples

Found some examples in the examples folder.

✨ API

geocode

Parameter Type Optional? Description
q String mandatory the query string to be geocoded: a placename, address or coordinates as lat,long
key String optional the key can be omitted when using a proxyURL or when using node with a dedicated environment variable
proxyURL String optional The proxy URL parameter (useful to hide your API key)

Error handling

API can return errors like invalid key, to many requests, daily quota exceeded, etc. Thoses errors are thrown as Javascript Error by the geocode function. The error object contains the same status object as the OpenCage API.

Assuming the catch statment uses error as variable name:

console.log('Error caught:', error.message);

will output for a 429:

Error caught: Too Many Requests

and

console.log(JSON.stringify(error, null, 2));

will output for a 429:

{
  "status": {
    "code": 429,
    "message": "Too Many Requests"
  }
}

Check the examples using the Test API key from OpenCage error handling examples

πŸ”¨ Build and test

  1. Fork or clone this repository
  2. $ cd into the repository folder
  3. $ npm install to install all the required dependencies from npm
  4. lint and test coverage using $ npm test
  5. Build : $ npm run build

πŸ›£ Revision History

Check the CHANGELOG file.

πŸ₯‚ Contributing

Anyone and everyone is welcome to contribute.

🐞 Issues

Find a bug or want to request a new feature? Please let me know by submitting an issue.

πŸ— Licensing

Licensed under the MIT License

A copy of the license is available in the repository's LICENSE file.

opencage-api-client's People

Contributors

0xflotus avatar dependabot[bot] avatar dhritzkiv avatar fossabot avatar freyfogle avatar greenkeeper[bot] avatar renovate[bot] avatar snyk-bot avatar tsamaya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

opencage-api-client's Issues

Implement AbortController/AbortSignal pattern

I was wondering if it would be useful to do a pull request implementing a version of the geocode call accepting an AbortSignal?

We use it to cancel requests that have not completed yet, for example when the user does a new search before the previous result is available. This improves performance and stops useless requests from being sent and then ignored.

prevent error in browser when api key is not set

With the new version passing the parameters (ie, not controlling a mandatory API key parameter) the behaviour is to read the environment variable. in a browser process.env is not defined and raise an error

Opencage options ex. Proximity

Hi! I am very grateful for this package as it has made it very easy to add the opencage API to my project however, I wanted to use the 'proximity' option that opencage suggests to bias my search results but I cannot see how I would do that with this package. Please let me know!

Thank you:)

how does proxy url work?

Hi @tsamaya
Thank you for this javascript library.
Can you explain somewhere how proxyUrl is working? You give some examples of the API using this but I don't understand what the proxy should send. If it's the API key, then what's the use? You can steal the key by running the proxy url, no?

update CI tests around fetch

httpbin and jsonplaceholde tend to be buggy then the CI is failing.

run a local server to test the fetch wrapper seems to be the way to go in order to be agnostic from any services

running the integration tests can also be demonstration of the fetch wrapper

Adding lat and lng value as q parameters return empty because of encodeURIComponent usage

when using q to add lat and lng values, the api return empty because encodeURIComponent encode the plus sign +, so it cannot be used with lat and lng.

the response I got is the following:

{
    "documentation": "https://opencagedata.com/api",
    "licenses": [
        {
            "name": "see attribution guide",
            "url": "https://opencagedata.com/credits"
        }
    ],
    "rate": {
        "limit": 2500,
        "remaining": 2494,
        "reset": 1600214400
    },
    "results": [],
    "status": {
        "code": 200,
        "message": "OK"
    },
    "stay_informed": {
        "blog": "https://blog.opencagedata.com",
        "twitter": "https://twitter.com/OpenCage"
    },
    "thanks": "For using an OpenCage API",
    "timestamp": {
        "created_http": "Tue, 15 Sep 2020 23:39:35 GMT",
        "created_unix": 1600213175
    },
    "total_results": 0
}

sending request without encode the plus sign works as expected.

upgrade deps

opencage-api-client git:(develop) npm outdated
Package                 Current   Wanted  Latest  Location
documentation            12.1.1   12.1.4  12.1.4  opencage-api-client
dotenv                    8.1.0    8.2.0   8.2.0  opencage-api-client
eslint                    6.1.0    6.8.0   6.8.0  opencage-api-client
eslint-config-prettier    6.0.0   6.10.0  6.10.0  opencage-api-client
eslint-plugin-import     2.18.2   2.20.1  2.20.1  opencage-api-client
eslint-plugin-jest      22.15.1  22.21.0  23.8.0  opencage-api-client
eslint-plugin-prettier    3.1.0    3.1.2   3.1.2  opencage-api-client
husky                     3.0.3    3.1.0   4.2.3  opencage-api-client
jest                     24.8.0   24.9.0  25.1.0  opencage-api-client
lint-staged               9.2.3    9.5.0  10.0.8  opencage-api-client
prettier                 1.18.2   1.19.1  1.19.1  opencage-api-client
webpack                  4.39.2   4.41.6  4.41.6  opencage-api-client
webpack-cli               3.3.7   3.3.11  3.3.11  opencage-api-client

update README.md

  • Other examples as a subtitle

  • TypeScript

  • Links on example page

TypeScript support (type definitions)

I recently created a project and used OpenCage Geocoder with a library called node-geocoder but it was using a few deprecated dependencies and I decided to use opencage-api-client instead.
opencage-api-client is pretty straightforward but it doesn't support TypeScript. In order to keep using it I had to create the type definitions.

https://github.com/calmonr/easycarros/blob/master/typings/opencage-api-client.d.ts#L2-L4

Unfortunately I don't have much time now to create a PR on DefinitelyTyped so we can have something like @types/opencage-api-client but you can do that if you want to support TypeScript by default.

I hope it helps.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/meterian.yml
  • actions/checkout v4
  • MeterianHQ/meterian-github-action v1.0.17
.github/workflows/node.js.yml
  • actions/checkout v4
  • pnpm/action-setup v3
  • actions/setup-node v4
  • codecov/codecov-action v4
npm
package.json
  • cross-fetch 4.0.0
  • dotenv 16.4.5
  • documentation ^14.0.0
  • eslint ^8.53.0
  • eslint-config-airbnb-base ^15.0.0
  • eslint-config-prettier ^9.0.0
  • eslint-plugin-import ^2.29.0
  • eslint-plugin-jest ^28.0.0
  • eslint-plugin-prettier ^5.0.1
  • husky ^9.0.0
  • jest ^29.7.0
  • lint-staged ^15.0.2
  • prettier ^3.0.3
  • webpack ^5.89.0
  • webpack-cli ^5.0.1

  • Check this box to trigger a request for Renovate to run again on this repository

improve unit tests

  • Avoid calling expect conditionally
  • Tests should use Jestβ€˜s exception helpers

new unit tests with API test keys

implement new unit tests with API keys for testing:

  • 6d0e711d72d74daeb2b0bfd2a5cdfdba which will always generate a 200 - OK response.
    Note the response will be as if the q parameter of the request had been 51.952659,7.632473 regardless of what was actually specified.
  • 4372eff77b8343cebfc843eb4da4ddc4 which will always generate a 402 - quota exceeded response.
  • 2e10e5e828262eb243ec0b54681d699a which will always generate a 403 - suspended response.
  • 6c79ee8e1ca44ad58ad1fc493ba9542f which will always generate a 403 - IP address rejected response.
  • d6d0f0065f4348a4bdfe4587ba02714b which will always generate a 429 - requesting too quickly response.

Check all informations at https://github.com/OpenCageData/opencagedata-misc-docs/blob/master/library-guidelines.md

Improve tests on the fetch wrapper

unit tests on fetch wrapper make requests to google/httpbin. Can we improve the unit tests to be isolated and avoid using an internet connection?

create-react-app build prod fails

When using this library in an application created with create-react-app, it is not possible to build a prod version of the application, the dev server is fine.

$ create-react-app --version
1.5.2

and this whatever version used :
browser version: import opencage from 'opencage-api-client/dist/opencage-api.min'; or node version : import opencage from 'opencage-api-client';`

  • browser version fails with
$ react-scripts build
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

 	./node_modules/opencage-api-client/dist/opencage-api.min.js:1:1324

Read more here: http://bit.ly/2tRViJ9

error Command failed with exit code 1.
  • node version fails with:
$ react-scripts build
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

 	./node_modules/opencage-api-client/src/helpers.js:7

Read more here: http://bit.ly/2tRViJ9

error Command failed with exit code 1.

document samples

Add a readme file explaining examples, linking to other repo for instance for typesript

TypeScript GeocodeOption is undefined

Based on library 0.8:

import { geocode, GeocodeRequest, GeocodeOption } from 'opencage-api-client';

export const doGeocode = async () => {
  const input: GeocodeRequest = {
    q: '51.952659,7.632473',
    key: '6d0e711d72d74daeb2b0bfd2a5cdfdba', // https://opencagedata.com/api#testingkeys
    no_annotations: GeocodeOption.Off,
  };
  const result = await geocode(input);
  console.log(result);
  return result;
};

raises TypeError: Cannot read property 'Off' of undefined

while this code is working

import { geocode, GeocodeRequest } from 'opencage-api-client';

export const doGeocode = async () => {
  const input: GeocodeRequest = {
    q: '51.952659,7.632473',
    key: '6d0e711d72d74daeb2b0bfd2a5cdfdba', // https://opencagedata.com/api#testingkeys
    no_annotations: 1,
  };
  const result = await geocode(input);
  console.log(result);
  return result;
};

drop any fetch dependencies

As now node since version 18 has a fetch() function built-in and all browsers have this function, I think it is time to get rid of dependencies. That would lighten the package and also narrow down security risks raised by Meterian's report with the old version of node-fetch used by cross-fetch

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.