Created
November 26, 2015 18:37
-
-
Save ryrych/cece6a13220a208ad469 to your computer and use it in GitHub Desktop.
After refactoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```javascript | |
import errorize from '../../../utils/errorize'; | |
import { module, test } from 'qunit'; | |
module('Unit | Utility | errorize'); | |
test('errorize', function(assert) { | |
var errors = { | |
responseJSON: { | |
errors:[ | |
{ | |
code:100, | |
title:'has already been taken', | |
detail:'Email has already been taken', | |
source:{ | |
pointer:'/data/attributes/email', | |
}, | |
}, | |
{ | |
code:100, | |
title:'is too short (minimum is 6 characters)', | |
detail:'Password is too short (minimum is 6 characters)', | |
source:{ | |
pointer:'/data/attributes/password', | |
}, | |
}, | |
], | |
}, | |
}; | |
var expected = { | |
email: [ | |
{message: 'Email has already been taken'}, | |
], | |
password: [ | |
{message: 'Password is too short (minimum is 6 characters)'}, | |
], | |
}; | |
let errorizeObject = errorize.create({errors}); | |
assert.deepEqual(errorizeObject.serialize(), expected, 'errorize should equal errors'); | |
}); | |
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```javascript | |
import Ember from 'ember'; | |
var errorize = Ember.Object.extend({ | |
init() { | |
this._super(); | |
this.set('errorsList', {}); | |
}, | |
passedErrorObject() { | |
return !Ember.isNone(this.get('errors')); | |
}, | |
buildErrorObjectFor(error) { | |
let field = this.getErrorObjectField(error); | |
let message = this.getErrorObjectMessage(error); | |
this.addOrCreateErrorForField(field, message); | |
}, | |
getErrorObjectField(error) { | |
// { source: { pointer:'/data/attributes/email' } } | |
return (/\w+$/.exec(error.source.pointer))[0].camelize(); | |
}, | |
getErrorObjectMessage(error) { | |
return error.detail; | |
}, | |
addOrCreateErrorForField(field, message) { | |
if (Ember.isNone(this.get('errorsList')[field])) { | |
this.get('errorsList')[field] = [{message}]; | |
} else { | |
this.get('errorsList')[field].push({message}); | |
} | |
}, | |
serialize() { | |
if (!this.passedErrorObject()) { | |
return {}; | |
} | |
this.get('errors.responseJSON.errors').forEach(error => this.buildErrorObjectFor(error)); | |
return this.get('errorsList'); | |
}, | |
}); | |
export default errorize; | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment