Skip to content

Instantly share code, notes, and snippets.

@ryrych
Created November 26, 2015 18:37
Show Gist options
  • Save ryrych/cece6a13220a208ad469 to your computer and use it in GitHub Desktop.
Save ryrych/cece6a13220a208ad469 to your computer and use it in GitHub Desktop.
After refactoring
```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');
});
```
```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