Socket
Socket
Sign inDemoInstall

mappersmith

Package Overview
Dependencies
Maintainers
1
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mappersmith - npm Package Compare versions

Comparing version 2.13.0 to 2.14.0

9

client-builder.js

@@ -26,3 +26,3 @@ 'use strict';

*/
function ClientBuilder(manifest, GatewayClassFactory, defaultGatewayConfigs, defaultMiddleware) {
function ClientBuilder(manifest, GatewayClassFactory, configs) {
if (!manifest) {

@@ -36,2 +36,6 @@ throw new Error('[Mappersmith] invalid manifest (' + manifest + ')');

var defaultGatewayConfigs = configs.gatewayConfigs;
var defaultMiddleware = configs.middleware;
this.context = configs.context;
this.manifest = new _manifest2.default(manifest, defaultGatewayConfigs, defaultMiddleware);

@@ -64,3 +68,4 @@ this.GatewayClassFactory = GatewayClassFactory;

invokeMiddlewares: function invokeMiddlewares(resourceName, resourceMethod, initialRequest) {
var middleware = this.manifest.createMiddleware({ resourceName: resourceName, resourceMethod: resourceMethod });
var context = (0, _utils.assign)({}, this.context);
var middleware = this.manifest.createMiddleware({ resourceName: resourceName, resourceMethod: resourceMethod, context: context });
var finalRequest = middleware.reduce(function (request, middleware) {

@@ -67,0 +72,0 @@ return middleware.request(request);

@@ -30,2 +30,3 @@ 'use strict';

this.host = obj.host;
this.clientId = obj.clientId || null;
this.gatewayConfigs = (0, _utils.assign)({}, defaultGatewayConfigs, obj.gatewayConfigs);

@@ -69,4 +70,6 @@ this.resources = obj.resources || {};

* @param {Object} args
* @param {String|Null} args.clientId
* @param {String} args.resourceName
* @param {String} args.resourceMethod
* @param {Object} args.context
* @param {Boolean} args.mockRequest

@@ -77,2 +80,4 @@ *

createMiddleware: function createMiddleware() {
var _this2 = this;
var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

@@ -88,3 +93,3 @@

}
}, middlewareFactory(args));
}, middlewareFactory((0, _utils.assign)(args, { clientId: _this2.clientId })));
};

@@ -91,0 +96,0 @@

@@ -6,3 +6,3 @@ 'use strict';

});
exports.configs = undefined;
exports.setContext = exports.configs = undefined;
exports.default = forge;

@@ -14,5 +14,8 @@

var _utils = require('./utils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var configs = exports.configs = {
context: {},
middleware: [],

@@ -85,9 +88,16 @@ Promise: typeof Promise === 'function' ? Promise : null,

/**
* @param {Object} manifest
* @param {Object} context
*/
};function forge(manifest) {
};var setContext = exports.setContext = function setContext(context) {
configs.context = (0, _utils.assign)(configs.context, context);
};
/**
* @param {Object} manifest
*/
function forge(manifest) {
var GatewayClassFactory = function GatewayClassFactory() {
return configs.gateway;
};
return new _clientBuilder2.default(manifest, GatewayClassFactory, configs.gatewayConfigs, configs.middleware).build();
return new _clientBuilder2.default(manifest, GatewayClassFactory, configs).build();
}
{
"name": "mappersmith",
"version": "2.13.0",
"version": "2.14.0",
"description": "It is a lightweight rest client for node.js and the browser",

@@ -5,0 +5,0 @@ "author": "Tulio Ornelas <ornelas.tulio@gmail.com>",

@@ -9,20 +9,31 @@ [![npm version](https://badge.fury.io/js/mappersmith.svg)](http://badge.fury.io/js/mappersmith)

1. [Installation](#installation)
1. [Usage](#usage)
1. [Commonjs](#commonjs)
1. [Configuring my resources](#resource-configuration)
1. [Parameters](#parameters)
1. [Default parameters](#default-parameters)
1. [Body](#body)
1. [Headers](#headers)
1. [Basic Auth](#basic-auth)
1. [Timeout](#timeout)
1. [Alternative host](#alternative-host)
1. [Binary data](#binary-data)
1. [Promises](#promises)
1. [Response object](#response-object)
1. [Middleware](#middleware)
1. [Testing Mappersmith](#testing-mappersmith)
1. [Gateways](#gateways)
1. [Development](#development)
- [Installation](#installation)
- [Usage](#usage)
- [Commonjs](#commonjs)
- [Configuring my resources](#resource-configuration)
- [Parameters](#parameters)
- [Default parameters](#default-parameters)
- [Body](#body)
- [Headers](#headers)
- [Basic Auth](#basic-auth)
- [Timeout](#timeout)
- [Alternative host](#alternative-host)
- [Binary data](#binary-data)
- [Promises](#promises)
- [Response object](#response-object)
- [Middleware](#middleware)
- [Global middleware](#global-middleware)
- [Context](#context)
- [Built-in middleware](#built-in-middleware)
- [BasicAuth](#middleware-basic-auth)
- [CSRF](#middleware-csrf)
- [Duration](#middleware-duration)
- [EncodeJSON](#middleware-encode-json)
- [GlobalErrorHandler](#middleware-global-error-handler)
- [Log](#middleware-log)
- [Retry](#middleware-retry)
- [Timeout](#middleware-timeout)
- [Testing Mappersmith](#testing-mappersmith)
- [Gateways](#gateways)
- [Development](#development)

@@ -65,2 +76,3 @@ ## <a name="installation"></a> Installation

const github = forge({
clientId: 'github',
host: 'https://status.github.com',

@@ -345,2 +357,3 @@ resources: {

const client = forge({
clientId: 'myClient',
middleware: [ MyMiddleware ],

@@ -355,6 +368,7 @@ resources: {

It can, optionally, receive the `resourceName` and `resourceMethod`, example:
It can, optionally, receive `resourceName`, `resourceMethod`, [#context](`context`)
and `clientId`. Example:
```javascript
const MyMiddleware = ({ resourceName, resourceMethod }) => ({
const MyMiddleware = ({ resourceName, resourceMethod, context, clientId }) => ({
/* ... */

@@ -366,5 +380,9 @@ })

// resourceMethod: 'all'
// clientId: 'myClient'
// context: {}
```
Finally, middleware can be defined globally, so new clients will automatically
### <a name="global-middleware"></a> Global middleware
Middleware can also be defined globally, so new clients will automatically
include the defined middleware:

@@ -376,11 +394,119 @@

configs.middleware = [MyMiddleware]
// all clients defined from now on will automatically include MyMiddleware
```
// all clients defined from now on will automatically include MyMiddleware
### <a name="context"></a> Context
Sometimes you may need to set data to be available to all your client's middleware. In this
case you can use the `setContext` helper, like so:
```javascript
import { setContext } from 'mappersmith'
const MyMiddleware = ({ context }) => ({
/* ... */
})
setContext({ some: 'data'})
client.User.all()
// context: { some: 'data' }
```
This is specially useful when using mappermith coupled with back-end services.
For instance you could define a globally available correlation id middleware
like this:
```javascript
import forge, { configs, setContext } from 'mappersmith'
import express from 'express'
const CorrelationIdMiddleware = ({ context }) => ({
request(request) {
return request.enhance({
headers: {
'correlation-id': context.correlationId
}
})
}
})
configs.middleware = [CorrelationIdMiddleware]
const api = forge({ ... })
const app = express()
app.use((req, res, next) => {
setContext({
correlationId: req.headers['correlation-id']
})
})
// Then, when calling `api.User.all()` in any handler it will include the
// `correlation-id` header automatically.
```
Note that setContext will merge the object provided with the current context
instead of replacing it.
### Built-in middleware
#### <a name="encode-json-middleware"></a> EncodeJson
#### <a name="middleware-basic-auth"></a> BasicAuth
Automatically configure your requests with basic auth
```javascript
import BasicAuthMiddleware from 'mappersmith/middleware/basic-auth'
const BasicAuth = BasicAuthMiddleware({ username: 'bob', password: 'bob' })
const client = forge({
middleware: [ BasicAuth ],
/* ... */
})
client.User.all()
// => header: "Authorization: Basic Ym9iOmJvYg=="
```
** The default auth can be overridden with the explicit use of the auth parameter, example:
```javascript
client.User.all({ auth: { username: 'bill', password: 'bill' } })
// auth will be { username: 'bill', password: 'bill' } instead of { username: 'bob', password: 'bob' }
```
#### <a name="middleware-csrf"></a> CSRF
Automatically configure your requests by adding a header with the value of a cookie - If it exists.
The name of the cookie (defaults to "csrfToken") and the header (defaults to "x-csrf-token") can be set as following;
```javascript
import CSRF from 'mappersmith/middleware/csrf'
const client = forge({
middleware: [ CSRF('csrfToken', 'x-csrf-token') ],
/* ... */
})
client.User.all()
```
#### <a name="middleware-duration"></a> Duration
Automatically adds `X-Started-At`, `X-Ended-At` and `X-Duration` headers to the response.
```javascript
import Duration from 'mappersmith/middleware/duration'
const client = forge({
middleware: [ Duration ],
/* ... */
})
client.User.all({ body: { name: 'bob' } })
// => headers: "X-Started-At=1492529128453;X-Ended-At=1492529128473;X-Duration=20"
```
#### <a name="middleware-encode-json"></a> EncodeJson
Automatically encode your objects into JSON

@@ -401,3 +527,3 @@

#### GlobalErrorHandler
#### <a name="middleware-global-error-handler"></a> GlobalErrorHandler

@@ -433,4 +559,17 @@ Provides a catch-all function for all requests. If the catch-all function returns `true` it prevents the original promise to continue.

#### Retry
#### <a name="middleware-log"></a> Log
Log all requests and responses. Might be useful in development mode.
```javascript
import Log from 'mappersmith/middleware/log'
const client = forge({
middleware: [ Log ],
/* ... */
})
```
#### <a name="middleware-retry"></a> Retry
This middleware will automatically retry GET requests up to the configured amount of retries using a randomization function that grows exponentially. The retry count and the time used will be included as a header in the response.

@@ -461,32 +600,8 @@

retries: 5, // max retries
validateRetry: () => true // a function that returns true if the request should be retried
validateRetry: (response) => true // a function that returns true if the request should be retried
})
```
#### <a name="basic-auth-middleware"></a> BasicAuth
#### <a name="middleware-timeout"></a> Timeout
Automatically configure your requests with basic auth
```javascript
import BasicAuthMiddleware from 'mappersmith/middleware/basic-auth'
const BasicAuth = BasicAuthMiddleware({ username: 'bob', password: 'bob' })
const client = forge({
middleware: [ BasicAuth ],
/* ... */
})
client.User.all()
// => header: "Authorization: Basic Ym9iOmJvYg=="
```
** The default auth can be overridden with the explicit use of the auth parameter, example:
```javascript
client.User.all({ auth: { username: 'bill', password: 'bill' } })
// auth will be { username: 'bill', password: 'bill' } instead of { username: 'bob', password: 'bob' }
```
#### <a name="timeout-middleware"></a> Timeout
Automatically configure your requests with a default timeout

@@ -513,47 +628,2 @@

#### Log
Log all requests and responses. Might be useful in development mode.
```javascript
import Log from 'mappersmith/middleware/log'
const client = forge({
middleware: [ Log ],
/* ... */
})
```
#### Duration
Automatically adds `X-Started-At`, `X-Ended-At` and `X-Duration` headers to the response.
```javascript
import Duration from 'mappersmith/middleware/duration'
const client = forge({
middleware: [ Duration ],
/* ... */
})
client.User.all({ body: { name: 'bob' } })
// => headers: "X-Started-At=1492529128453;X-Ended-At=1492529128473;X-Duration=20"
```
#### <a name="csrf-middleware"></a> Csrf
Automatically configure your requests by adding a header with the value of a cookie - If it exists.
The name of the cookie (defaults to "csrfToken") and the header (defaults to "x-csrf-token") can be set as following;
```javascript
import Csrf from 'mappersmith/middleware/csrf'
const client = forge({
middleware: [ Csrf('csrfToken', 'x-csrf-token') ],
/* ... */
})
client.User.all()
```
## <a name="testing-mappersmith"></a> Testing Mappersmith

@@ -560,0 +630,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc