Skip to content
This repository was archived by the owner on May 27, 2021. It is now read-only.

Commit

Permalink
[API-964] Ky rewrite (#133)
Browse files Browse the repository at this point in the history
* wip

* fuck fetch and the horse it rode in on

* axios=>ky resources

* Fix uglifyjs

* Almost done

* Remove axios tests

* Disable test stage for now

* File downloads

* Fix header parsing

* Use ky-universal

* Cancelable promises

* allow for passing custom signal

* re-add methods

* Fix sending http bodies

* Add makeCancelable helper

* typo

* Add makeCancelable helper to some of the required places

* Add makeCancelable helper everywhere

* lint

* docs

* more docs

* Odds and ends

* Fix docs

* make unobservable protected again

* Remove deprecated code

* Implement API-932

* Remove job monitor code

* Rename Maps4News -> Mapcreator

* Make ApiError use getters

* Fix Choropleth::getJson

* CancelablePromise docs

* Fixes for docs

* Use Class in jsdoc

* Fixes for docs

* ky docs

* Fixes for docs

* Fixes for docs

* Fixes for docs

* ApiError

* Fix throw error syntax

* Upgrade documentation

* Formatting on tests

* Fix most tests

* enable tests

* Fix last tests

Co-authored-by: Kevin Richter <[email protected]>
  • Loading branch information
Mechazawa and beschoenen authored Aug 11, 2020
1 parent 1a918d3 commit e56a0ef
Show file tree
Hide file tree
Showing 66 changed files with 1,502 additions and 2,752 deletions.
12 changes: 3 additions & 9 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
# Api host
HOST=https://api.maps4news.com

# Default perPage value for listings
PER_PAGE=12

# Window options for the ImplicitFlowPopup
WINDOW_OPTIONS=width=800, height=600

# Show deleted items, possible values (none, only, all)
# Requires special api permissions
SHOW_DELETED=none

# Default perPage value for listings
PER_PAGE=12

# JobMonitor max rows
JOB_MONITOR_MAX_ROWS=100

# Cache
CACHE_SHARED=true
CACHE_SECONDS=1800
CACHE_SHARED_AUTO_UPDATE=true
CACHE_DEREFERENCE_OUTPUT=false

# debug, info, warn, error
LOG_LEVEL=warn
9 changes: 3 additions & 6 deletions .env.test
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
# Api host
HOST=https://api.maps4news.com

# Default perPage value for listings
PER_PAGE=12

# Window options for the ImplicitFlowPopup
WINDOW_OPTIONS=width=800, height=600

# Show deleted items, possible values (none, only, all)
# Requires special api permissions
SHOW_DELETED=none

# Default perPage value for listings
PER_PAGE=12

# JobMonitor max rows
JOB_MONITOR_MAX_ROWS=100

# Cache
CACHE_SHARED=false

# debug, info, warn, error
LOG_LEVEL=debug
2 changes: 1 addition & 1 deletion Jenkinsfile
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ node('npm') {
PACKAGE_VERSION = sh(returnStdout: true, script: 'git describe --exact-match --tag HEAD 2>/dev/null || git rev-parse --short HEAD').trim()
println "Published package version ${PACKAGE_VERSION}"

slackSend(color: 'good', message: "`@mapcreator/maps4news` version ${PACKAGE_VERSION} was just published, please run `npm install @mapcreator/maps4news${PACKAGE_VERSION.replace('v', '@')}`.", channel: '#api')
slackSend(color: 'good', message: "`@mapcreator/api` version ${PACKAGE_VERSION} was just published, please run `npm install @mapcreator/api${PACKAGE_VERSION.replace('v', '@')}`.", channel: '#api')
}
}

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Maps4News Javascript API [![npm version](https://img.shields.io/npm/v/@mapcreator/maps4news.svg)](https://www.npmjs.com/package/@mapcreator/maps4news)
Mapcreator Javascript API [![npm version](https://img.shields.io/npm/v/@mapcreator/api.svg)](https://www.npmjs.com/package/@mapcreator/api)
-------------------------

The Maps4News API is a powerful mapping service built for our front-end applications. This library is released to
The Mapcreator API is a powerful mapping service built for our front-end applications. This library is released to
provide a painless way of talking to the api using Javascript. See the [LICENSE] file for licensing information. Api
tokens can be granted through support requests.

Expand Down
12 changes: 12 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Upgrading from @mapcreator/maps4news
------------------------------------

The following changes are important to keep in mind when upgrading from
`@mapcreator/maps4news` to `@mapcreator/api`.

- `JobMonitor`, `JobMonitorRow` and `JobMonitorFilter` classes have been removed
- `PaginatedResourceWrapper` and `ResourceCache` classes have been removed
- This also removes the `PaginatedResourceListing::wrap` and `SimpleResourceProxy::listAndWrap` methods
- `Maps4News` class has been renamed to `Mapcreator`
- Most methods that return Promises can now be canceled using the `CancelablePromise` type
- `axios` has been deprecated in favor of `ky`. This means that calls like `api.axios.get()` need to be rewritten
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ module.exports = {
coverageDirectory: 'build/coverage',
reporters: [
'default',
['jest-junit', {outputDirectory: 'build'}],
['jest-junit', { outputDirectory: 'build' }],
],
setupFiles: [
'<rootDir>/tests/setup.js',
Expand Down
38 changes: 19 additions & 19 deletions manual/examples.authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ Authentication is done through [OAuth]. This library provides multiple [OAuth fl
implementations for authentication. A client id can be obtained through a support
ticket but this is planned to change in the near future. The client will first
check if any tokens can be found in the cache before requiring authentication.
If one can be found the `api.authenticate()` method will instantly resolve without
If one can be found the `api.authenticate()` method will instantly resolve without
any side-effects. The variable `api.authenticated` will be set to true if a token
has been found and is still valid.
has been found and is still valid.

Tokens are stored in HTTPS cookies if possible and using `localStorage` when the
browser is not using a HTTPS connection. [Nodejs] uses a file named `.m4n_token` to store the token.
Expand All @@ -15,8 +15,8 @@ Multiple flows are supported for web browsers. All the web examples assume the w
build of the library has been included in the target page.

### Implicit Flow
A client id is required to use the implicit flow. The redirect url *must* be the
same as the one linked to the client id. The callback url is automatically
A client id is required to use the implicit flow. The redirect url *must* be the
same as the one linked to the client id. The callback url is automatically
guessed if none is provided.

```js
Expand All @@ -25,22 +25,22 @@ var clientId = 1;

// Callback url is set to the current url by default
var auth = new ImplicitFlow(clientId);
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

// This will hijack the page if no authentication cache can
// be found. Smartest thing to do is to just let it happen
// and initialize any other code afterwards.
api.authenticate().then(function() {
// Save the token
api.saveToken();

// Get the current user and dump the result to the console.
api.users.get('me').then(console.dir);
});
```

### Implicit flow pop-up
Just like the Implicit Flow a client id is required.
Just like the Implicit Flow a client id is required.

```js
// Obtained client id
Expand All @@ -53,23 +53,23 @@ var clientId = 1;
// a custom page that just contains `api.authenticate()`
// that uses ImplicitFlowPopup as the auth parameter.
var auth = new ImplicitFlowPopup(clientId);
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

// This will create a pop-up window containing the log in
// page. Once the pop-up redirects back to the callback it
// will resolve the promise. The callback page should contain
api.authenticate().then(function() {
// Save the token
api.saveToken();

// Get the current user and dump the result to the console.
api.users.get('me').then(console.dir);
});
```

### Implicit flow pop-up (advanced)
Due to the nature of the implicit flow pop-up (referred to as IFP from now on)
method the callback page can be set to a blank page that just grabs the token
method the callback page can be set to a blank page that just grabs the token
and then closes. This can be done in the following way.

**index.html:**
Expand All @@ -79,13 +79,13 @@ var clientId = 1;
var callbackUrl = 'https://example.com/callback.html';

var auth = new ImplicitFlowPopup(clientId);
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

// This will resolve once the callback page has been loaded
api.authenticate().then(function() {
// Save the token
api.saveToken();

// Get the current user and dump the result to the console.
api.users.get('me').then(console.dir);
});
Expand All @@ -101,8 +101,8 @@ new ImplicitFlowPopup(clientId);
```

### Password flow (dangerous)
The password flow is **NOT** intended to be used in the browser. If you do
decide to use the password flow then it is recommended to make sure that
The password flow is **NOT** intended to be used in the browser. If you do
decide to use the password flow then it is recommended to make sure that
the site is **NOT** public facing and using HTTPS. Leaking the [secret] is
a very bad idea.

Expand All @@ -115,7 +115,7 @@ var password = 'Password1!'; // password
// Secret will be leaked if this is used on a webpage. Please only use
// this for non-web applications.
var auth = new PasswordFlow(clientId, secret, username, password);
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

// This will resolve once the authentication has completed
api.authenticate().then(function() {
Expand All @@ -125,11 +125,11 @@ api.authenticate().then(function() {
```

### Dummy flow
The dummy flow can be used when a token *should* be present in the cache.
The dummy flow can be used when a token *should* be present in the cache.

```js
var auth = new DummyFlow();
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

// Manually check if we're logged in
if (api.authenticated) {
Expand Down Expand Up @@ -160,7 +160,7 @@ var username = '[email protected]'; // email is used for authentication
var password = 'Password1!'; // password

var auth = new PasswordFlow(clientId, secret, username, password);
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

// This will resolve once the authentication has completed
api.authenticate().then(function() {
Expand All @@ -174,7 +174,7 @@ The dummy flow can also be used when a token is known.

```js
var auth = new DummyFlow();
var api = new Maps4News(auth);
var api = new Mapcreator(auth);

var token = {
token: "eyJ0eXAiOiJKV1...",
Expand Down
46 changes: 30 additions & 16 deletions manual/examples.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# Basics
These examples assume that an instance of the api exists and is authenticated.
These examples assume that an instance of the api exists and is authenticated.
See the node and web authentication examples for more information on authenticating.

### Getting a resource
Resources are bound to the base api class by default. Resources can be fetched in
Resources are bound to the base api class by default. Resources can be fetched in
two ways; by selecting them (`.select`) or by fetching them (`.get`). Selecting them will only set the
object's id to it's properties. Fetching a resource

Fetch resource and all it's properties:

```js
```js
api.colors.get(1).then(function(color) {
console.log(color.id + " " + color.name + ": " + color.hex);
})
Expand All @@ -25,7 +25,7 @@ api.users.select('me').mapstyleSets().then(function(sets) {
});
```

Selection is only usefull as a stepping stone to related resources that can be easily obtained
Selection is only usefull as a stepping stone to related resources that can be easily obtained
using the id of the parent. Please refer to the [api documentation] for further reference.

### Create a new resource
Expand All @@ -47,7 +47,7 @@ api.users.get('me').then(me => {
```

### Clone a resource
Setting the id to null forces the creation of a new object upon saving.
Setting the id to null forces the creation of a new object upon saving.

```js
api.colors.get(1).then(color => {
Expand All @@ -67,16 +67,16 @@ api.colors.list(1, 5).then(page => {
console.log(page.data[i].toString());
}
});
```
```

Loop over every page and print the result to the console.

```js
function parsePages(page) {
for (var i = 0; i < page.data.length; i++) {
console.log(page.data[i].toString());
}
console.log(page.data[i].toString());
}

if (page.hasNext) {
console.log('Grabbing page ' + (page.page + 1));
page.next().then(parsePage);
Expand All @@ -93,17 +93,17 @@ Loop over all pages and return the data in a promise
```js
function parsePages(page) {
var data = [];

function parse(page) {
data = data.concat(page.data);

if(page.hasNext) {
return page.next().then(parse);
} else {
return data;
}
}
}

return parse(page);
}

Expand Down Expand Up @@ -133,7 +133,21 @@ var query = {
api.layers.search(query).then(console.dir);
```

The `search` method is an extension of `list`. This means that `.search({})` is the same as
The `search` method is an extension of `list`. This means that `.search({})` is the same as
`list()`. More information about search query formatting can be found in the [api documentation].

[api documepntation]: https://docs.maps4news.com/

### Canceling a requests
Most methods that return a promise will have a method called `cancel`. This method can be called
to cancel the request. If the request is running or about to be ran the promise will throw an error
once canceled. If the request has been completed before the promise has been canceled it will not
throw an error and instead complete successfully.

```js
// Fetch a preview
const promise = api.jobs.select(123456).downloadPreview();

// Turns out we don't need it anyways
promise.cancel();
```

[api documentation]: https://docs.maps4news.com/
12 changes: 6 additions & 6 deletions manual/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,30 @@ Installation can be done through either [npm] or [yarn].

```sh
// Using npm
npm install --save @mapcreator/maps4news
npm install --save @mapcreator/api

// Using yarn
yarn add @mapcreator/maps4news
yarn add @mapcreator/api
```

After installation the package can be imported as follows:

```js
var m4n = require('@mapcreator/maps4news');
var m4n = require('@mapcreator/api');

// Do stuff
var auth = new m4n.ImplicitFlow(1);
var api = new m4n.Maps4News(auth);
```

or using ES6 import statements:

```js
import {Maps4News, DummyFlow} from '@mapcreator/maps4news';
import {Mapcreator, DummyFlow} from '@mapcreator/api';

// Do stuff
var auth = new DummyFlow();
var api = new Maps4News(auth);
var api = new Mapcreator(auth);
```

[npm]: https://npmjs.com
Expand Down
Loading

0 comments on commit e56a0ef

Please sign in to comment.