Skip to content

Instantly share code, notes, and snippets.

@FerrielMelarpis
Last active September 15, 2017 03:40
Show Gist options
  • Save FerrielMelarpis/795bca3c55534fb610351eac36a001a4 to your computer and use it in GitHub Desktop.
Save FerrielMelarpis/795bca3c55534fb610351eac36a001a4 to your computer and use it in GitHub Desktop.
OOP Vue
// lib/Errors.js
import _ from 'lodash';
export default class Errors {
constructor() {
this.errors = {};
}
has(field) {
return _.has(this.errors, field);
}
get any() {
return _.size(this.errors) > 0;
}
// can be overriden by extending the class to have modified access to errors object
get(field) {
_.get(this.errors, field);
}
record(errors) {
this.errors = errors;
}
clear(field) {
if (field) {
delete this.errors[field];
return;
}
this.errors = {};
}
}
// lib/Form.js
/**
* extend this class to add validation rules then later on pass in vue validations
* e.g.
* import {...} from 'vuelidate/lib/validators';
*
* class VideoSubmissionForm extends Form {
* constructor() {
* super(...arguments);
* }
*
* get $validationRules() {
* return {
* ...
* };
* }
* }
* ...
* // in some component
* export default {
* data () {
* return {
* form: new VideoSubmissionForm(),
* }
* }
* validations: this.form.$validationRules,
* }
*/
import _ from 'lodash';
import axios from 'axios';
import Errors from './Errors';
export default class Form {
constructor(data) {
this._data = data;
this.$errors = new Errors();
this.$lastSuccess = null;
for (let field in data) {
this[field] = data[field];
}
}
$data(fields = []) {
const formData = this._data;
if (fields.length) {
return _.pick(formData, fields);
}
let data = {};
for (let field in formData) {
data[field] = this[field];
}
return data;
}
$reset() {
for (let field in this._data) {
this[field] = '';
}
this.$errors.clear();
}
$post(url) {
return this.submit('post', url);
}
$put(url) {
return this.submit('put', url);
}
$patch(url) {
return this.submit('patch', url);
}
$delete(url) {
return this.submit('delete', url);
}
$submit(method, url, headers = {}) {
const requestOptions = _.merge(this.$data(), { headers });
return new Promise((resolve, reject) => {
axios[_.toLower(method)](url, requestOptions)
.then(response => {
this.$onSuccess(response);
resolve(response);
})
.catch(error => {
this.$onFail(error);
reject(error);
});
});
}
$onSuccess(data) {
this.$lastSuccess = data;
this.$reset();
}
$onFail(errors) {
this.$errors.record(errors);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment