Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

redux-api-middleware

Package Overview
Dependencies
Maintainers
2
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

redux-api-middleware - npm Package Compare versions

Comparing version 3.0.0-beta.3 to 3.0.0-beta.4

lib/index.cjs.js

13

es/errors.js

@@ -15,4 +15,4 @@ /**

}
}
/**

@@ -25,2 +25,4 @@ * Error class for a custom `payload` or `meta` function throwing

*/
class InternalError extends Error {

@@ -32,4 +34,4 @@ constructor(message) {

}
}
/**

@@ -42,2 +44,4 @@ * Error class for an error raised trying to make an API call

*/
class RequestError extends Error {

@@ -49,4 +53,4 @@ constructor(message) {

}
}
/**

@@ -62,2 +66,4 @@ * Error class for an API response outside the 200 range

*/
class ApiError extends Error {

@@ -72,4 +78,5 @@ constructor(status, statusText, response) {

}
}
export { InvalidRSAA, InternalError, RequestError, ApiError };
// Public package exports
import { InvalidRSAA, InternalError, RequestError, ApiError } from './index.js';
import { InvalidRSAA, InternalError, RequestError, ApiError } from 'redux-api-middleware';
describe('InvalidRSAA', () => {
const validationErrors = ['validation error 1', 'validation error 2'];
const error = new InvalidRSAA(validationErrors);
it('is an error object', () => {
expect(error).toBeInstanceOf(Error);
});
it('matches snapshot', () => {

@@ -17,10 +14,7 @@ expect(error).toMatchSnapshot();

});
describe('InternalError', () => {
const error = new InternalError('error thrown in payload function');
it('is an error object', () => {
expect(error).toBeInstanceOf(Error);
});
it('matches snapshot', () => {

@@ -31,10 +25,7 @@ expect(error).toMatchSnapshot();

});
describe('RequestError', () => {
const error = new RequestError('Network request failed');
it('is an error object', () => {
expect(error).toBeInstanceOf(Error);
});
it('matches snapshot', () => {

@@ -45,11 +36,10 @@ expect(error).toMatchSnapshot();

});
describe('ApiError', () => {
const json = { error: 'Resource not found' };
const json = {
error: 'Resource not found'
};
const error = new ApiError(404, 'Not Found', json);
it('is an error object', () => {
expect(error).toBeInstanceOf(Error);
});
it('matches snapshot', () => {

@@ -56,0 +46,0 @@ expect(error).toMatchSnapshot();

@@ -31,3 +31,2 @@ /**

*/
import RSAA from './RSAA';

@@ -38,3 +37,2 @@ import { isRSAA, validateRSAA, isValidRSAA } from './validation';

import { apiMiddleware, createMiddleware } from './middleware';
export { RSAA, isRSAA, validateRSAA, isValidRSAA, InvalidRSAA, InternalError, RequestError, ApiError, getJSON, createMiddleware, apiMiddleware };

@@ -1,3 +0,5 @@

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import RSAA from './RSAA';

@@ -7,3 +9,2 @@ import { isRSAA, validateRSAA } from './validation';

import { normalizeTypeDescriptors, actionWith } from './util';
/**

@@ -14,2 +15,3 @@ * Default options for redux-api-middleware

*/
const defaults = {

@@ -19,3 +21,2 @@ ok: res => res.ok,

};
/**

@@ -29,6 +30,8 @@ * A middleware creator used to create a ReduxApiMiddleware

*/
function createMiddleware(options = {}) {
const middlewareOptions = Object.assign({}, defaults, options);
return ({ getState }) => next => action => {
return ({
getState
}) => next => action => {
// Do not process actions without an [RSAA] property

@@ -42,9 +45,13 @@ if (!isRSAA(action)) {

const validationErrors = validateRSAA(action);
if (validationErrors.length) {
const callAPI = action[RSAA];
if (callAPI.types && Array.isArray(callAPI.types)) {
let requestType = callAPI.types[0];
if (requestType && requestType.type) {
requestType = requestType.type;
}
next({

@@ -56,6 +63,7 @@ type: requestType,

}
return;
}
} // Parse the validated RSAA action
// Parse the validated RSAA action
const callAPI = action[RSAA];

@@ -70,6 +78,10 @@ var {

} = callAPI;
const { method, credentials, bailout, types } = callAPI;
const [requestType, successType, failureType] = normalizeTypeDescriptors(types);
const {
method,
credentials,
bailout,
types
} = callAPI;
const [requestType, successType, failureType] = normalizeTypeDescriptors(types); // Should we bail out?
// Should we bail out?
try {

@@ -80,9 +92,9 @@ if (typeof bailout === 'boolean' && bailout || typeof bailout === 'function' && bailout(getState())) {

} catch (e) {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new RequestError('[RSAA].bailout function failed'),
error: true
}), [action, getState()])));
}
} // Process [RSAA].endpoint function
// Process [RSAA].endpoint function
if (typeof endpoint === 'function') {

@@ -92,3 +104,3 @@ try {

} catch (e) {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new RequestError('[RSAA].endpoint function failed'),

@@ -98,5 +110,5 @@ error: true

}
}
} // Process [RSAA].body function
// Process [RSAA].body function
if (typeof body === 'function') {

@@ -106,3 +118,3 @@ try {

} catch (e) {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new RequestError('[RSAA].body function failed'),

@@ -112,5 +124,5 @@ error: true

}
}
} // Process [RSAA].headers function
// Process [RSAA].headers function
if (typeof headers === 'function') {

@@ -120,3 +132,3 @@ try {

} catch (e) {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new RequestError('[RSAA].headers function failed'),

@@ -126,5 +138,5 @@ error: true

}
}
} // Process [RSAA].options function
// Process [RSAA].options function
if (typeof options === 'function') {

@@ -134,3 +146,3 @@ try {

} catch (e) {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new RequestError('[RSAA].options function failed'),

@@ -140,5 +152,5 @@ error: true

}
}
} // We can now dispatch the request FSA
// We can now dispatch the request FSA
if (typeof requestType.payload === 'function' || typeof requestType.meta === 'function') {

@@ -151,5 +163,6 @@ next((await actionWith(requestType, [action, getState()])));

let res;
try {
// Make the API call
res = await doFetch(endpoint, _extends({}, options, {
res = await doFetch(endpoint, _objectSpread({}, options, {
method,

@@ -162,3 +175,3 @@ body: body || undefined,

// The request was malformed, or there was a network error
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new RequestError(e.message),

@@ -170,16 +183,17 @@ error: true

let isOk;
try {
isOk = ok(res);
} catch (e) {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
payload: new InternalError('[RSAA].ok function failed'),
error: true
}), [action, getState(), res])));
}
} // Process the server response
// Process the server response
if (isOk) {
return next((await actionWith(successType, [action, getState(), res])));
} else {
return next((await actionWith(_extends({}, failureType, {
return next((await actionWith(_objectSpread({}, failureType, {
error: true

@@ -191,3 +205,2 @@ }), [action, getState(), res])));

}
/**

@@ -199,6 +212,12 @@ * A Redux middleware that processes RSAA actions.

*/
function apiMiddleware({ getState }) {
return createMiddleware()({ getState });
function apiMiddleware({
getState
}) {
return createMiddleware()({
getState
});
}
export { createMiddleware, apiMiddleware };

@@ -1,17 +0,25 @@

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
// Public package exports
import { RSAA, apiMiddleware, createMiddleware, InternalError } from './index.js';
import { RSAA, apiMiddleware, createMiddleware, InternalError } from 'redux-api-middleware';
const fetchMockSnapshotMatcher = {
invocationCallOrder: expect.any(Object)
};
// const fetchMockSnapshotMatcher = {};
}; // const fetchMockSnapshotMatcher = {};
const doTestMiddleware = async ({ response, action }) => {
const doTestMiddleware = async ({
response,
action
}) => {
if (response) {
const { body } = response,
mockConfig = _objectWithoutProperties(response, ['body']);
const {
body
} = response,
mockConfig = _objectWithoutProperties(response, ["body"]);
fetch.mockResponseOnce(body, mockConfig);

@@ -24,4 +32,5 @@ }

doNext.mockImplementation(it => it);
const nextHandler = apiMiddleware({ getState: doGetState });
const nextHandler = apiMiddleware({
getState: doGetState
});
const actionHandler = nextHandler(doNext);

@@ -32,2 +41,3 @@ const result = actionHandler(action);

const final = await result;
if (final) {

@@ -60,13 +70,15 @@ expect(final).toMatchSnapshot({}, 'final result');

const doGetState = () => {};
const middleware = createMiddleware();
const nextHandler = middleware({ getState: doGetState });
const nextHandler = middleware({
getState: doGetState
});
const doNext = () => {};
const actionHandler = nextHandler(doNext);
expect(typeof middleware).toEqual('function');
expect(middleware).toHaveLength(1);
expect(typeof nextHandler).toEqual('function');
expect(nextHandler).toHaveLength(1);
expect(typeof actionHandler).toEqual('function');

@@ -76,24 +88,25 @@ expect(actionHandler).toHaveLength(1);

});
describe('#apiMiddleware', () => {
it('is a redux middleware', () => {
const doGetState = () => {};
const nextHandler = apiMiddleware({ getState: doGetState });
const nextHandler = apiMiddleware({
getState: doGetState
});
const doNext = () => {};
const actionHandler = nextHandler(doNext);
expect(typeof apiMiddleware).toEqual('function');
expect(apiMiddleware).toHaveLength(1);
expect(typeof nextHandler).toEqual('function');
expect(nextHandler).toHaveLength(1);
expect(typeof actionHandler).toEqual('function');
expect(actionHandler).toHaveLength(1);
});
it('must pass actions without an [RSAA] property to the next handler', async () => {
const action = {};
const { doNext } = await doTestMiddleware({
const {
doNext
} = await doTestMiddleware({
action

@@ -103,23 +116,22 @@ });

});
it("mustn't return a promise on actions without a [RSAA] property", async () => {
const action = {};
const { result } = await doTestMiddleware({
const {
result
} = await doTestMiddleware({
action
});
expect(result.then).toBeUndefined();
});
it('must return a promise on actions without a [RSAA] property', async () => {
const action = { [RSAA]: {} };
const { result } = await doTestMiddleware({
const action = {
[RSAA]: {}
};
const {
result
} = await doTestMiddleware({
action
});
expect(typeof result.then).toEqual('function');
});
it('must dispatch an error request FSA for an invalid RSAA with a string request type', async () => {

@@ -131,3 +143,2 @@ const action = {

};
await doTestMiddleware({

@@ -137,3 +148,2 @@ action

});
it('must dispatch an error request FSA for an invalid RSAA with a descriptor request type', async () => {

@@ -147,3 +157,2 @@ const action = {

};
await doTestMiddleware({

@@ -153,3 +162,2 @@ action

});
it('must do nothing for an invalid RSAA without a request type', async () => {

@@ -159,10 +167,9 @@ const action = {

};
const { doNext } = await doTestMiddleware({
const {
doNext
} = await doTestMiddleware({
action
});
expect(doNext).not.toHaveBeenCalled();
});
it('must dispatch an error request FSA when [RSAA].bailout fails', async () => {

@@ -183,3 +190,2 @@ const action = {

};
await doTestMiddleware({

@@ -189,3 +195,2 @@ action

});
it('must dispatch an error request FSA when [RSAA].body fails', async () => {

@@ -206,3 +211,2 @@ const action = {

};
await doTestMiddleware({

@@ -212,3 +216,2 @@ action

});
it('must dispatch an error request FSA when [RSAA].endpoint fails', async () => {

@@ -228,3 +231,2 @@ const action = {

};
await doTestMiddleware({

@@ -234,3 +236,2 @@ action

});
it('must dispatch an error request FSA when [RSAA].headers fails', async () => {

@@ -251,3 +252,2 @@ const action = {

};
await doTestMiddleware({

@@ -257,3 +257,2 @@ action

});
it('must dispatch an error request FSA when [RSAA].options fails', async () => {

@@ -274,3 +273,2 @@ const action = {

};
await doTestMiddleware({

@@ -280,3 +278,2 @@ action

});
it('must dispatch an error request FSA when [RSAA].ok fails', async () => {

@@ -293,7 +290,8 @@ const action = {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -306,6 +304,4 @@ headers: {

});
it('must dispatch a failure FSA with an error on a request error', async () => {
fetch.mockRejectOnce(new Error('Test request error'));
const action = {

@@ -322,3 +318,2 @@ [RSAA]: {

};
await doTestMiddleware({

@@ -328,3 +323,2 @@ action

});
it('must use an [RSAA].bailout boolean when present', async () => {

@@ -339,3 +333,2 @@ const action = {

};
await doTestMiddleware({

@@ -345,7 +338,5 @@ action

});
it('must use an [RSAA].bailout function when present', async () => {
const bailout = jest.fn();
bailout.mockReturnValue(true);
const action = {

@@ -359,7 +350,10 @@ [RSAA]: {

};
const { doNext } = await doTestMiddleware({
const {
doNext
} = await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -371,11 +365,8 @@ headers: {

});
expect(bailout).toMatchSnapshot({}, 'bailout()');
expect(doNext).not.toHaveBeenCalled();
});
it('must use an [RSAA].body function when present', async () => {
const body = jest.fn();
body.mockReturnValue('mockBody');
const action = {

@@ -389,7 +380,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -401,10 +393,7 @@ headers: {

});
expect(body).toMatchSnapshot({}, 'body()');
});
it('must use an [RSAA].endpoint function when present', async () => {
const endpoint = jest.fn();
endpoint.mockReturnValue('http://127.0.0.1/api/users/1');
const action = {

@@ -417,7 +406,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -429,10 +419,9 @@ headers: {

});
expect(endpoint).toMatchSnapshot({}, 'endpoint()');
});
it('must use an [RSAA].headers function when present', async () => {
const headers = jest.fn();
headers.mockReturnValue({ 'Test-Header': 'test' });
headers.mockReturnValue({
'Test-Header': 'test'
});
const action = {

@@ -446,7 +435,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -458,10 +448,7 @@ headers: {

});
expect(headers).toMatchSnapshot({}, 'headers()');
});
it('must use an [RSAA].options function when present', async () => {
const options = jest.fn();
options.mockReturnValue({});
const action = {

@@ -475,7 +462,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -487,10 +475,7 @@ headers: {

});
expect(options).toMatchSnapshot({}, 'options()');
});
it('must use an [RSAA].ok function when present', async () => {
const ok = jest.fn();
ok.mockReturnValue(true);
const action = {

@@ -504,7 +489,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -516,10 +502,7 @@ headers: {

});
expect(ok).toMatchSnapshot({}, 'ok()');
});
it('must dispatch a failure FSA when [RSAA].ok returns false on a successful request', async () => {
const ok = jest.fn();
ok.mockReturnValue(false);
const action = {

@@ -533,7 +516,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -545,6 +529,4 @@ headers: {

});
expect(ok).toMatchSnapshot({}, 'ok()');
});
it('must use a [RSAA].fetch custom fetch wrapper when present', async () => {

@@ -554,4 +536,3 @@ const myFetch = async (endpoint, opts) => {

const json = await res.json();
return new Response(JSON.stringify(_extends({}, json, {
return new Response(JSON.stringify(_objectSpread({}, json, {
foo: 'bar'

@@ -575,3 +556,2 @@ })), {

};
await doTestMiddleware({

@@ -592,3 +572,2 @@ action,

});
it('must dispatch correct error payload when [RSAA].fetch wrapper returns an error response', async () => {

@@ -614,3 +593,2 @@ const myFetch = async (endpoint, opts) => {

};
await doTestMiddleware({

@@ -620,7 +598,5 @@ action

});
it('must use payload property of request type descriptor when it is a function', async () => {
const payload = jest.fn();
payload.mockReturnValue('requestPayload');
const action = {

@@ -637,7 +613,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -649,10 +626,7 @@ headers: {

});
expect(payload).toMatchSnapshot({}, 'payload()');
});
it('must use meta property of request type descriptor when it is a function', async () => {
const meta = jest.fn();
meta.mockReturnValue('requestMeta');
const action = {

@@ -669,7 +643,8 @@ [RSAA]: {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ data: '12345' }),
body: JSON.stringify({
data: '12345'
}),
status: 200,

@@ -681,6 +656,4 @@ headers: {

});
expect(meta).toMatchSnapshot({}, 'meta()');
});
it('must dispatch a success FSA on a successful API call with a non-empty JSON response', async () => {

@@ -701,7 +674,8 @@ const action = {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ username: 'Alice' }),
body: JSON.stringify({
username: 'Alice'
}),
status: 200,

@@ -714,3 +688,2 @@ headers: {

});
it('must dispatch a success FSA on a successful API call with an empty JSON response', async () => {

@@ -731,3 +704,2 @@ const action = {

};
await doTestMiddleware({

@@ -744,3 +716,2 @@ action,

});
it('must dispatch a success FSA with an error state on a successful API call with an invalid JSON response', async () => {

@@ -764,3 +735,2 @@ const action = {

};
await doTestMiddleware({

@@ -777,3 +747,2 @@ action,

});
it('must dispatch a success FSA on a successful API call with a non-JSON response', async () => {

@@ -794,3 +763,2 @@ const action = {

};
await doTestMiddleware({

@@ -804,3 +772,2 @@ action,

});
it('must dispatch a failure FSA on an unsuccessful API call with a non-empty JSON response', async () => {

@@ -821,7 +788,8 @@ const action = {

};
await doTestMiddleware({
action,
response: {
body: JSON.stringify({ error: 'Resource not found' }),
body: JSON.stringify({
error: 'Resource not found'
}),
status: 404,

@@ -834,3 +802,2 @@ headers: {

});
it('must dispatch a failure FSA on an unsuccessful API call with an empty JSON response', async () => {

@@ -851,3 +818,2 @@ const action = {

};
await doTestMiddleware({

@@ -864,3 +830,2 @@ action,

});
it('must dispatch a failure FSA on an unsuccessful API call with a non-JSON response', async () => {

@@ -881,3 +846,2 @@ const action = {

};
await doTestMiddleware({

@@ -884,0 +848,0 @@ action,

@@ -9,3 +9,2 @@ /**

const RSAA = '@@redux-api-middleware/RSAA';
export default RSAA;

@@ -1,5 +0,6 @@

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { InternalError, ApiError } from './errors';
/**

@@ -13,2 +14,3 @@ * Extract JSON body from a server response

*/
async function getJSON(res) {

@@ -24,3 +26,2 @@ const contentType = res.headers.get('Content-Type');

}
/**

@@ -35,2 +36,4 @@ * Blow up string or symbol types into full-fledged type descriptors,

*/
function normalizeTypeDescriptors(types) {

@@ -40,9 +43,14 @@ let [requestType, successType, failureType] = types;

if (typeof requestType === 'string' || typeof requestType === 'symbol') {
requestType = { type: requestType };
requestType = {
type: requestType
};
}
if (typeof successType === 'string' || typeof successType === 'symbol') {
successType = { type: successType };
successType = {
type: successType
};
}
successType = _extends({
successType = _objectSpread({
payload: (action, state, res) => getJSON(res)

@@ -52,11 +60,12 @@ }, successType);

if (typeof failureType === 'string' || typeof failureType === 'symbol') {
failureType = { type: failureType };
failureType = {
type: failureType
};
}
failureType = _extends({
failureType = _objectSpread({
payload: (action, state, res) => getJSON(res).then(json => new ApiError(res.status, res.statusText, json))
}, failureType);
return [requestType, successType, failureType];
}
/**

@@ -71,2 +80,4 @@ * Evaluate a type descriptor to an FSA

*/
async function actionWith(descriptor, args = []) {

@@ -73,0 +84,0 @@ try {

// Public package exports
import { RSAA, getJSON } from './index.js';
import { RSAA, getJSON } from './index.js'; // Private package import
// Private package import
import { normalizeTypeDescriptors, actionWith } from './util';
describe('#normalizeTypeDescriptors', () => {

@@ -13,3 +11,2 @@ it('handles string types', () => {

});
it('handles object types', () => {

@@ -33,3 +30,2 @@ const types = [{

});
describe('#actionWith', () => {

@@ -43,6 +39,4 @@ it('handles string payload and meta descriptor properties', async () => {

});
expect(fsa).toMatchSnapshot();
});
it('handles function payload and meta descriptor properties', async () => {

@@ -56,3 +50,2 @@ const fsa = await actionWith({

});
it('passes function payload and meta descriptor properties arguments', async () => {

@@ -63,3 +56,2 @@ const payload = jest.fn();

meta.mockReturnValue('someMetaFromMock');
const passedArgs = ['action', 'state', 'res'];

@@ -71,7 +63,5 @@ const fsa = await actionWith({

}, passedArgs);
expect(payload).toHaveBeenCalledWith(...passedArgs);
expect(meta).toHaveBeenCalledWith(...passedArgs);
});
it('handles an error in the payload function', async () => {

@@ -84,6 +74,4 @@ const fsa = await actionWith({

});
expect(fsa).toMatchSnapshot();
});
it('handles an error in the meta function', async () => {

@@ -96,6 +84,4 @@ const fsa = await actionWith({

});
expect(fsa).toMatchSnapshot();
});
it('handles a synchronous payload function', async () => {

@@ -106,6 +92,4 @@ const fsa = await actionWith({

});
expect(fsa).toMatchSnapshot();
});
it('handles an asynchronous payload function', async () => {

@@ -116,6 +100,4 @@ const fsa = await actionWith({

});
expect(fsa).toMatchSnapshot();
});
it('handles a synchronous meta function', async () => {

@@ -126,6 +108,4 @@ const fsa = await actionWith({

});
expect(fsa).toMatchSnapshot();
});
it('handles an asynchronous meta function', async () => {

@@ -136,7 +116,5 @@ const fsa = await actionWith({

});
expect(fsa).toMatchSnapshot();
});
});
describe('#getJSON', () => {

@@ -149,12 +127,15 @@ it("returns the JSON body of a response with a JSONy 'Content-Type' header", async () => {

}
},
json() {
return Promise.resolve({ message: 'ok' });
return Promise.resolve({
message: 'ok'
});
}
};
const result = await getJSON(res);
expect(result).toMatchSnapshot();
});
it("returns a resolved promise for a response with a not-JSONy 'Content-Type' header", async () => {

@@ -166,2 +147,3 @@ const res = {

}
}

@@ -168,0 +150,0 @@ };

import RSAA from './RSAA';
/**

@@ -11,6 +10,6 @@ * Is the argument a plain object?

*/
function isPlainObject(obj) {
return obj && typeof obj == 'object' && Object.getPrototypeOf(obj) === Object.prototype;
}
/**

@@ -24,6 +23,7 @@ * Is the given action a plain JavaScript object with an [RSAA] property?

*/
function isRSAA(action) {
return isPlainObject(action) && action.hasOwnProperty(RSAA);
}
/**

@@ -37,2 +37,4 @@ * Is the given object a valid type descriptor?

*/
function isValidTypeDescriptor(obj) {

@@ -44,2 +46,3 @@ const validKeys = ['type', 'payload', 'meta'];

}
for (let key in obj) {

@@ -50,2 +53,3 @@ if (!~validKeys.indexOf(key)) {

}
if (!('type' in obj)) {

@@ -59,3 +63,2 @@ return false;

}
/**

@@ -70,2 +73,4 @@ * Checks an action against the RSAA definition, returning a (possibly empty)

*/
function validateRSAA(action) {

@@ -83,5 +88,7 @@ var validationErrors = [];

const callAPI = action[RSAA];
if (!isPlainObject(callAPI)) {
validationErrors.push('[RSAA] property must be a plain JavaScript object');
}
for (let key in callAPI) {

@@ -104,2 +111,3 @@ if (!~validCallAPIKeys.indexOf(key)) {

} = callAPI;
if (typeof endpoint === 'undefined') {

@@ -110,2 +118,3 @@ validationErrors.push('[RSAA] must have an endpoint property');

}
if (typeof method === 'undefined') {

@@ -122,5 +131,7 @@ validationErrors.push('[RSAA] must have a method property');

}
if (typeof options !== 'undefined' && !isPlainObject(options) && typeof options !== 'function') {
validationErrors.push('[RSAA].options property must be undefined, a plain JavaScript object, or a function');
}
if (typeof credentials !== 'undefined') {

@@ -133,2 +144,3 @@ if (typeof credentials !== 'string') {

}
if (typeof bailout !== 'undefined' && typeof bailout !== 'boolean' && typeof bailout !== 'function') {

@@ -144,8 +156,11 @@ validationErrors.push('[RSAA].bailout property must be undefined, a boolean, or a function');

const [requestType, successType, failureType] = types;
if (typeof requestType !== 'string' && typeof requestType !== 'symbol' && !isValidTypeDescriptor(requestType)) {
validationErrors.push('Invalid request type');
}
if (typeof successType !== 'string' && typeof successType !== 'symbol' && !isValidTypeDescriptor(successType)) {
validationErrors.push('Invalid success type');
}
if (typeof failureType !== 'string' && typeof failureType !== 'symbol' && !isValidTypeDescriptor(failureType)) {

@@ -170,3 +185,2 @@ validationErrors.push('Invalid failure type');

}
/**

@@ -180,2 +194,4 @@ * Is the given action a valid RSAA?

*/
function isValidRSAA(action) {

@@ -182,0 +198,0 @@ return !validateRSAA(action).length;

@@ -0,7 +1,6 @@

import "core-js/modules/es7.symbol.async-iterator";
// Public package exports
import { RSAA, isRSAA, validateRSAA, isValidRSAA } from './index.js';
import { RSAA, isRSAA, validateRSAA, isValidRSAA } from 'redux-api-middleware'; // Private package import
// Private package import
import { isValidTypeDescriptor } from './validation';
describe('#isValidTypeDescriptor', () => {

@@ -12,3 +11,2 @@ it('must be a plain JavaScript object', () => {

});
it('must not have properties other than type, payload and meta', () => {

@@ -21,3 +19,2 @@ var descriptor = {

});
it('must have a type property', () => {

@@ -27,3 +24,2 @@ var descriptor = {};

});
it('must not have a type property that is not a string or a symbol', () => {

@@ -35,3 +31,2 @@ var descriptor = {

});
it('may have a type property that is a string', () => {

@@ -43,3 +38,2 @@ var descriptor = {

});
it('may have a type property that is a symbol', () => {

@@ -52,3 +46,2 @@ var descriptor = {

});
describe('#isRSAA', () => {

@@ -58,12 +51,11 @@ it('RSAAs must be plain JavaScript objects', () => {

});
it('RSAAs must have an [RSAA] property', () => {
expect(isRSAA({})).toBeFalsy();
});
it('returns true for an RSAA', () => {
expect(isRSAA({ [RSAA]: {} })).toBeTruthy();
expect(isRSAA({
[RSAA]: {}
})).toBeTruthy();
});
});
describe('#validateRSAA / #isValidRSAA', () => {

@@ -74,3 +66,2 @@ it('handles invalid actions', () => {

});
it('handles invalid RSAA value (string)', () => {

@@ -80,16 +71,14 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid RSAA value (invalid object)', () => {
const action = {
[RSAA]: { invalidKey: '' }
[RSAA]: {
invalidKey: ''
}
};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles missing RSAA properties', () => {

@@ -99,7 +88,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].endpoint property', () => {

@@ -113,7 +100,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].method property (object)', () => {

@@ -127,7 +112,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].method property (invalid string)', () => {

@@ -141,7 +124,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].headers property', () => {

@@ -156,7 +137,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].credentials property (object)', () => {

@@ -171,7 +150,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].credentials property (invalid string)', () => {

@@ -186,7 +163,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].bailout property', () => {

@@ -201,7 +176,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].types property (object)', () => {

@@ -215,7 +188,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].types property (wrong length)', () => {

@@ -229,7 +200,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].types property (invalid objects)', () => {

@@ -243,7 +212,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].options property', () => {

@@ -258,7 +225,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].fetch property', () => {

@@ -273,7 +238,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles invalid [RSAA].ok property', () => {

@@ -288,7 +251,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeFalsy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with endpoint string', () => {

@@ -302,7 +263,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with endpoint function', () => {

@@ -316,7 +275,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with headers object', () => {

@@ -331,7 +288,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with headers function', () => {

@@ -346,7 +301,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with bailout boolean', () => {

@@ -361,7 +314,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with bailout function', () => {

@@ -376,7 +327,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with types of symbols', () => {

@@ -390,7 +339,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with types of type descriptors', () => {

@@ -416,7 +363,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with options object', () => {

@@ -431,7 +376,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with options function', () => {

@@ -446,7 +389,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles valid RSAA with fetch function', () => {

@@ -461,7 +402,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles top-level string properties other than RSAA', () => {

@@ -476,7 +415,5 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();
expect(validateRSAA(action)).toMatchSnapshot();
});
it('handles top-level symbol properties other than RSAA', () => {

@@ -491,3 +428,2 @@ const action = {

};
expect(isValidRSAA(action)).toBeTruthy();

@@ -494,0 +430,0 @@ expect(validateRSAA(action)).toMatchSnapshot();

{
"name": "redux-api-middleware",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"description": "Redux middleware for calling an API.",
"source": "src/index.js",
"main": "lib/index.js",
"main": "lib/index.cjs.js",
"browser": "lib/index.umd.js",

@@ -11,9 +10,10 @@ "module": "es/index.js",

"scripts": {
"build": "babel src --out-dir es && microbundle --entry src/index.js --compress false --strict --format cjs,umd",
"build": "babel src --out-dir es && rollup -c",
"postbuild": "npm run size",
"clean": "rimraf es lib coverage",
"test": "cross-env BABEL_ENV=test jest",
"test": "cross-env NODE_ENV=test jest src es",
"test:build": "cross-env TEST_LIB=true NODE_ENV=test jest src",
"cover": "npm test -- --verbose --coverage --collectCoverageFrom \"src/**/*.js\"",
"lint": "eslint src",
"prepublishOnly": "npm run lint && npm test && npm run clean && npm run build",
"prepublishOnly": "npm run lint && npm test && npm run clean && npm run build && npm run test:build",
"size": "size-limit"

@@ -37,5 +37,6 @@ },

"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"@babel/cli": "^7.0.0-beta.54",
"@babel/core": "^7.0.0-beta.54",
"@babel/preset-env": "^7.0.0-beta.54",
"babel-core": "^7.0.0-bridge.0",
"coveralls": "^3.0.1",

@@ -48,5 +49,8 @@ "cross-env": "^5.2.0",

"jest-fetch-mock": "^1.6.5",
"microbundle": "^0.5.1",
"prettier": "^1.13.5",
"rimraf": "^2.6.2",
"rollup": "^0.63.4",
"rollup-plugin-babel": "^4.0.0-beta.7",
"rollup-plugin-commonjs": "^9.1.3",
"rollup-plugin-node-resolve": "^3.3.0",
"size-limit": "^0.18.2"

@@ -59,12 +63,3 @@ },

"lib"
],
"jest": {
"automock": false,
"resetMocks": true,
"restoreMocks": true,
"resetModules": true,
"setupFiles": [
"./test/setupJest.js"
]
}
]
}

Sorry, the diff of this file is too big to display

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