Skip to content

Refactor index.js & add more tests #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion spec/helpers.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ context('Helpers', () => {
it('should format a time given a Date object', () => {
const time = new Date('December 25, 1995 23:15:30');
expect(formatTime(time)).to.equal('23:15:30.000');
});
});
});
});
47 changes: 37 additions & 10 deletions spec/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,54 @@ context('default logger', () => {
});

context('createLogger', () => {
describe('init', () => {
beforeEach(() => {
sinon.spy(console, 'error');
sinon.spy(console, 'log');
});

afterEach(() => {
console.error.restore();
console.log.restore();
});

let store;

context('mistakenly passed directly to applyMiddleware', () => {
beforeEach(() => {
sinon.spy(console, 'error');
store = createStore(() => ({}), applyMiddleware(createLogger));
});

afterEach(() => {
console.error.restore();
it('should log error', () => {
sinon.assert.calledOnce(console.error);
});

it('should throw error if passed direct to applyMiddleware', () => {
const store = createStore(() => ({}), applyMiddleware(createLogger));
it('should create an empty middleware', () => {
store.dispatch({ type: 'foo' });
sinon.assert.notCalled(console.log);
});
});

context('options.logger undefined or null', () => {
beforeEach(() => {
const logger = createLogger({ logger: null });
store = createStore(() => ({}), applyMiddleware(logger));
});

it('should create an empty middleware', () => {
store.dispatch({ type: 'foo' });
sinon.assert.calledOnce(console.error);
sinon.assert.notCalled(console.log);
});
});

it('should be ok', () => {
const store = createStore(() => ({}), applyMiddleware(createLogger()));
context('options.predicate returns false', () => {
beforeEach(() => {
const logger = createLogger({ predicate: () => false });
store = createStore(() => ({}), applyMiddleware(logger));
});

it('should not log', () => {
store.dispatch({ type: 'foo' });
sinon.assert.notCalled(console.error);
sinon.assert.notCalled(console.log);
});
});
});
105 changes: 58 additions & 47 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,29 @@ import defaults from './defaults';
*
* @returns {function} logger middleware
*/
function createLogger(options = {}) {
const loggerOptions = Object.assign({}, defaults, options);
function directlyApplied(options) {
return !!(options.getState && options.dispatch);
}

const {
logger,
stateTransformer,
errorTransformer,
predicate,
logErrors,
diffPredicate,
} = loggerOptions;
function hasLogger(options) {
return options.logger;
}

// Return if 'console' object is not defined
if (typeof logger === 'undefined') {
return () => next => action => next(action);
}
function shouldNotLog({ predicate }, getState, action) {
return !!(typeof predicate === 'function' && !predicate(getState, action));
}

// Detect if 'createLogger' was passed directly to 'applyMiddleware'.
if (options.getState && options.dispatch) {
// eslint-disable-next-line no-console
console.error(`[redux-logger] redux-logger not installed. Make sure to pass logger instance as middleware:
function shouldDiff({ diff, diffPredicate }, getState, action) {
return !!(diff && typeof diffPredicate === 'function' && diffPredicate(getState, action));
}

function emptyLogger() {
return () => next => action => next(action);
}

function emptyLoggerWarning() {
// eslint-disable-next-line no-console
console.error(`[redux-logger] redux-logger not installed. Make sure to pass logger instance as middleware:
// Logger with default options
import { logger } from 'redux-logger'
const store = createStore(
Expand All @@ -58,49 +60,58 @@ const store = createStore(
applyMiddleware(logger)
)
`);
}

return () => next => action => next(action);
function createLogger(options = {}) {
// Detect if 'createLogger' was passed directly to 'applyMiddleware'.
if (directlyApplied(options)) {
emptyLoggerWarning();
return emptyLogger();
}

const logBuffer = [];
const loggerOptions = Object.assign({}, defaults, options);

// Return if 'console' object is not defined
if (!hasLogger(loggerOptions)) return emptyLogger();

return ({ getState }) => next => (action) => {
// Exit early if predicate function returns 'false'
if (typeof predicate === 'function' && !predicate(getState, action)) {
return next(action);
}

const logEntry = {};

logBuffer.push(logEntry);

logEntry.started = timer.now();
logEntry.startedTime = new Date();
logEntry.prevState = stateTransformer(getState());
logEntry.action = action;
if (shouldNotLog(options, getState, action)) return next(action);

const started = timer.now();
const startedTime = new Date();
const prevState = loggerOptions.stateTransformer(getState());
let returnedValue;
if (logErrors) {
try {
returnedValue = next(action);
} catch (e) {
logEntry.error = errorTransformer(e);
}
} else {
let error;

try {
returnedValue = next(action);
} catch (e) {
if (loggerOptions.logErrors) {
error = loggerOptions.errorTransformer(e);
} else {
throw e;
}
}

logEntry.took = timer.now() - logEntry.started;
logEntry.nextState = stateTransformer(getState());
const took = timer.now() - started;
const nextState = loggerOptions.stateTransformer(getState());

const diff = loggerOptions.diff && typeof diffPredicate === 'function'
? diffPredicate(getState, action)
: loggerOptions.diff;
loggerOptions.diff = shouldDiff(loggerOptions, getState, action);

printBuffer(logBuffer, Object.assign({}, loggerOptions, { diff }));
logBuffer.length = 0;
printBuffer(
[{
started,
startedTime,
prevState,
action,
error,
took,
nextState,
}],
loggerOptions);

if (logEntry.error) throw logEntry.error;
if (error) throw error;
return returnedValue;
};
}
Expand Down