api-mount-client

1.0.13 • Public • Published

api-mount-client

by Vytenis Urbonavičius

api-mount-client provides a straightforward way for reaching back-end API served using api-mount-server or a compatible library.

Once setup, it makes it feel as if server-side API methods are called directly.

This library is based on api-link which is dedicating request functionality to either browser's fetch API or a node-fetch in a Node environment.


Installation

Consider using a more universal library - api-mount. api-mount contains both server and client code in one package. Usage and available methods are identical to api-mount-client. Only package name differs.

If you want to continue using a client-only version:

npm install --save api-mount-client

Usage

On your Node server build an object containing API methods (more information and alternative ways of constructing API are provided in the docs of api-mount-server):

const api = {
  foo() {
    return 'foo'
  },
}

In case your back-end is not based on Node but you would still want to use api-mount-client, you can explore Protocol section in the docs of api-mount-server.

Expose API via api-mount-server (see docs of api-mount-server to explore different approaches, usage of classes, namespacing, etc.):

const {apiMountFactory} = require('api-mount-server')
const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)

In case you have client and server on different hosts/ports, you might run into browser's CORS policy restrictions. Unless handled requests may get blocked or responses may be incomplete. Below is an example using cors NPM package for working around browser's CORS policy constraint:

const ApiMount = apiMountFactory({
  beforeListen: app => {
    // This is just for testing purposes
    // You would probably want to explicitly list
    // where you expect requests to be coming from
    // for security reasons
    app.use(require('cors')())
  },
})

On client side (browser or Node client) mount the API:

import {mountApi} from 'api-mount-client'
const api = mountApi({baseUrl: 'http://someServer.com:3000'})

If your API is namespaced, attach your namespace path to the baseUrl of mountApi:

const api = mountApi({baseUrl: 'http://someServer.com:3000/api-name'})

Now you can access function on server from your client just like that:

const result = await api.foo() // 'foo'

Note that client always receives a Promise object. This is why await was used. In case foo rejects a promise or throws an exception, client will reject a promise with error as a payload.

Try it out!

In order to test library on vanilla JavaScript directly in browser, you can refer to this example:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script src="./node_modules/api-mount-client/dist/index.js"></script> 
  </head>
  <body>
    <script>
      const api = window.ApiMountClient.mountApi({
        baseUrl: 'http://localhost:3000',
      })
 
      api.test().then(console.log)
    </script> 
  </body>
</html>

api-mount-client is exposed as a UMD library and therefore it is available in global scope if no other way of importing is available.

Above example assumes that API was exposed using Node code like this:

const {apiMountFactory} = require('api-mount-server')
var cors = require('cors')
 
const ApiMount = apiMountFactory({
  beforeListen: app => app.use(cors()),
})
 
const api = {
  test = () => 'works!',
}
 
ApiMount.exposeApi(api)

Supported Configuration

mountApi supports a configuration which contains following keys:

  • baseUrl - base URL for HTTP requests. It may contain a protocol, host, port and base path but should not contain end-point method names and/or query arguments.
  • fetchConfig - fetch API configuration which is passed through to the browser's fetch API or a server-side equivalent. Additional documentation can be found under /docs directory inside api-link package. One common case of using fetchConfig is to modify headers. Please note that provided headers completely override default ones. Please make sure that Content-Type is provided correctly. Normally it should be setup for JSON usage:
// ...
  fetchConfig{
    requestInit{
      headers{
        'Content-Type''application/json',
        // Other headers may go here
      },
    },
  },
// ...

Package Sidebar

Install

npm i api-mount-client

Weekly Downloads

0

Version

1.0.13

License

MIT

Unpacked Size

325 kB

Total Files

21

Last publish

Collaborators

  • white-turbine