What is mappersmith?
Mappersmith is a lightweight HTTP client library for JavaScript that simplifies the process of making HTTP requests. It provides a declarative way to define API endpoints and offers features like middleware support, request/response transformation, and retries.
What are mappersmith's main functionalities?
Declarative API Definition
Mappersmith allows you to define your API endpoints in a declarative manner. This example shows how to define a client with endpoints for fetching all users and fetching a user by ID.
const { forge } = require('mappersmith');
const api = forge({
clientId: 'my-api',
host: 'https://api.example.com',
resources: {
User: {
all: { path: '/users' },
byId: { path: '/users/{id}' }
}
}
});
api.User.all().then(response => console.log(response.data));
Middleware Support
Mappersmith supports middleware, allowing you to intercept and modify requests and responses. This example demonstrates how to log requests and responses using middleware.
const { forge, configs } = require('mappersmith');
configs.middleware = [
(request) => {
console.log('Request:', request);
return request;
},
(response) => {
console.log('Response:', response);
return response;
}
];
const api = forge({
clientId: 'my-api',
host: 'https://api.example.com',
resources: {
User: {
all: { path: '/users' }
}
}
});
api.User.all().then(response => console.log(response.data));
Request/Response Transformation
Mappersmith allows you to transform requests and responses. This example shows how to transform the response to extract user names from the list of users.
const { forge } = require('mappersmith');
const api = forge({
clientId: 'my-api',
host: 'https://api.example.com',
resources: {
User: {
all: { path: '/users', transform: (response) => response.data.map(user => user.name) }
}
}
});
api.User.all().then(userNames => console.log(userNames));
Retries
Mappersmith provides built-in support for retrying failed requests. This example configures the client to retry failed requests up to 3 times with exponential backoff.
const { forge, configs } = require('mappersmith');
configs.retry = { retries: 3, factor: 2, minTimeout: 1000 };
const api = forge({
clientId: 'my-api',
host: 'https://api.example.com',
resources: {
User: {
all: { path: '/users' }
}
}
});
api.User.all().then(response => console.log(response.data));
Other packages similar to mappersmith
axios
Axios is a popular promise-based HTTP client for JavaScript. It offers a simple API for making HTTP requests and supports features like interceptors, request/response transformation, and automatic JSON parsing. Compared to Mappersmith, Axios is more widely used and has a larger community, but it does not provide a declarative way to define API endpoints.
fetch
Fetch is a built-in web API for making HTTP requests in modern browsers. It provides a low-level API for making requests and handling responses. While Fetch is more lightweight and has no external dependencies, it lacks the higher-level abstractions and features like middleware and retries that Mappersmith offers.
superagent
Superagent is a small, progressive HTTP request library for Node.js and browsers. It provides a flexible API for making HTTP requests and supports features like plugins, request/response transformation, and retries. Compared to Mappersmith, Superagent is more flexible but requires more manual setup for defining API endpoints.
Mappersmith
Mappersmith is a lightweight, dependency-free, rest client mapper for javascript. It helps you map your API to use at the client, giving you all the flexibility you want to customize requests or write your own gateways.
Install
NPM
npm install mappersmith
Browser
Download the tag/latest version from the build folder.
Build from the source
Install the dependencies
npm install
Build
npm run build
Usage
To create a client for your API, you will need to provide a simple manifest, which must have host
and resources
keys. Each resource has a name and a list of methods with its definitions, like:
var manifest = {
host: 'http://my.api.com',
resources: {
Book: {
all: {path: '/v1/books.json'},
byId: {path: '/v1/books/{id}.json'}
},
Photo: {
byCategory: {path: '/v1/photos/{category}/all.json'}
}
}
}
You can specify an HTTP method for every API call, but if you don't, GET
will be used. For instance, let's say you can save a photo:
...
Photo: {
save: {method: 'POST', path: '/v1/photos/{category}/save'}
}
...
With the manifest in your hands, you are able to forge your client:
var Client = new Mappersmith.forge(manifest)
And then, use it as defined:
Client.Book.byId({id: 3})
Client.Book.byId({id: 3}, function(data) {
}).fail(function() {
}).complete(function() {
})
Parameters
If your method doesn't require any parameter, you can just call it without them:
Client.Book.all()
Every parameter that doesn't match a pattern ({parameter-name}
) in path
will be sent as part of the query string:
Client.Book.all({language: 'en'})
Gateways
Mappersmith allows you to customize the transport layer. You can use the default Mappersmith.VanillaGateway
, the included Mappersmith.JQueryGateway
or write your own version.
How to write one?
var MyGateway = function() {
return Mappersmith.Gateway.apply(this, arguments);
}
MyGateway.prototype = Mappersmith.Utils.extend({},
Mappersmith.Gateway.prototype, {
get: function() {
},
post: function() {
}
})
How to change the default?
Just provide an implementation of Mappersmith.Gateway
as the second argument of the method forge
:
var Client = new Mappersmith.forge(manifest, Mappersmith.JQueryGateway)
Specifics of each gateway
You can pass options for the gateway implementation that you are using. For example, if we are using the Mappersmith.JQueryGateway
and want one of our methods to use jsonp
, we can call it like:
Client.Book.byId({id: 2}, function(data) {}, {jsonp: true})
The third argument is passed to the gateway as this.opts
and, of course, the accepted options vary by each implementation. The default gateway, Mappersmith.VanillaGateway
, accepts a configure
callback:
Client.Book.byId({id: 2}, function(data) {}, {
configure: function(request) {
}
})
Gateway Implementations
The gateways listed here are available through the Mappersmith
namespace.
VanillaGateway
The default gateway - it uses plain XMLHttpRequest
. Accepts a configure
callback that allows you to change the request object before it is used.
Available methods:
- :ok: GET
- :x: POST
- :x: PUT
- :x: DELETE
- :x: PATCH
JQueryGateway
It uses $.ajax
and accepts an object that will be merged with defaults
. It doesn't include jquery, so you will need to include that in your page.
Available methods:
- :ok: GET
- :x: POST
- :x: PUT
- :x: DELETE
- :x: PATCH
Tests
- Build the source (
npm run build
) - Open test.html
Licence
See LICENCE for more details.