Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Created October 13, 2016 18:45
Show Gist options
  • Save abiodun0/6aec8264b5a4ef1f2ad1a08b111da704 to your computer and use it in GitHub Desktop.
Save abiodun0/6aec8264b5a4ef1f2ad1a08b111da704 to your computer and use it in GitHub Desktop.
Normalizing user data with classess.. Needs refactoring
import { _ } from 'underscore'
import { classify } from 'underscore.string'
String.prototype.lowercaseFirstLetter = function () {
return this.charAt(0).toLowerCase() + this.slice(1);
};
function delegate(model, delegations = []) {
delegations.forEach(delegation => {
let classifyProperty = classify(delegation.property);
delegation.methods.forEach(delegationMethod => {
let prefixName = delegationMethod.startsWith('is') ? 'is' : 'get';
let methodName = `${prefixName}${classifyProperty}${classify(delegationMethod.replace(/(is|get)/, ''))}`;
let returnable = `(this._${delegation.property} && this._${delegation.property}.${delegationMethod} && this._${delegation.property}.${delegationMethod}()) || undefined`;
model[`${methodName}`] = new Function(`return function ${methodName}() { return ${returnable}; }`)();
});
});
}
function relationships(model, relations = [], attributes = {}) {
relations.forEach(relation => {
let methodName;
let attribute;
if (relation['hasOne']) {
methodName = `get${classify(relation['hasOne'])}`;
attribute = relation['hasOne'];
if (attributes[relation['attributeKey']]) {
model[`_${attribute}`] = new relation['model'](attributes[relation['attributeKey']]);
}
} else if (relation['hasMany']) {
methodName = `get${classify(relation['hasMany'])}`;
attribute = relation['hasMany'];
if (!_.isEmpty(attributes[relation['attributeKey']])) {
model[`_${attribute}`] = relation['model']['fromArray'](attributes[relation['attributeKey']]);
}
}
model[methodName] = new Function(`return function ${methodName}() { return this._${attribute}; }`)();
});
}
class BaseModel {
constructor(attributes = {}) {
attributes && Object.keys(attributes).forEach(key => {
const classifyAttribute = classify(key);
const attributeName = classifyAttribute.lowercaseFirstLetter();
if (typeof attributes[key] !== 'object' || !attributes[key]) {
const prefixName = typeof attributes[key] === 'boolean' ? 'is' : 'get';
this[`_${attributeName}`] = attributes[key];
this[`${prefixName}${classifyAttribute}`] = new Function(`return function ${prefixName}${classifyAttribute}() { return this._${attributeName} ; }`)();
}
});
relationships(this, this.relations(), attributes);
delegate(this, this.delegations());
}
relations() {
return [];
}
delegations() {
return [];
}
}
export default BaseModel;
import { _ } from 'underscore'
import { stripAndLowerCase, generateNumString } from '../utils/string'
import BaseModel from './BaseModel'
import Organization from './Organization'
import Role from './Role'
import Address from './Address'
import PatientSafety from './PatientSafety'
import FamilyPhysician from './FamilyPhysician'
import InsuranceProvider from './InsuranceProvider'
const ADMIN = 'admin';
const PATIENT = 'Patient';
const PHYSICIAN = 'Physician';
const MANAGER = 'Manager';
const OWNER = 'Owner';
function hasRole(type, roles) {
return roles.filter(role => role.is(type)).length > 0;
}
class User extends BaseModel {
static fromArray = function (users) {
return users.map(user => new User(user));
};
static generateUsername = function (name) {
return `${stripAndLowerCase(name)}${generateNumString()}`;
};
constructor(attributes = {}) {
super(attributes);
}
relations() {
return [
{hasOne: 'address', model: Address, attributeKey: 'address'},
{hasOne: 'avatar', model: BaseModel, attributeKey: 'avatar'},
{hasOne: 'billingAddress', model: Address, attributeKey: 'billing_address'},
{hasOne: 'organization', model: Organization, attributeKey: 'organization'},
{hasOne: 'patientSafety', model: PatientSafety, attributeKey: 'patient_safety_attributes'},
{hasOne: 'familyPhysician', model: FamilyPhysician, attributeKey: 'family_physician_attributes'},
{hasMany: 'insuranceProviders', model: InsuranceProvider, attributeKey: 'insurance_providers_attributes'},
{hasMany: 'roles', model: Role, attributeKey: 'roles'}
];
}
delegations() {
return [
{methods: ['isCareProvider', 'isCareReceiver'], property: 'organization'},
{methods: ['toString'], property: 'address'},
{methods: ['getName', 'getPhoneNumber', 'getEmail'], property: 'patientSafety'},
{methods: ['getNormal', 'getThumb', 'getSmallThumb'], property: 'avatar'}
];
}
getSplitableBirthday() {
this._splitableBirthday = this._splitableBirthday || this._dateOfBirth ? this._dateOfBirth.split('-') : null;
return this._splitableBirthday;
}
getUsername() {
return this._username;
}
isAdmin() {
this._isAdmin = this._isAdmin || hasRole(ADMIN, this._roles);
return this._isAdmin;
}
isManager() {
this._isManager = this._isManager || hasRole(MANAGER, this._roles);
return this._isManager;
}
isOwner() {
this._isOwner = this._isOwner || hasRole(OWNER, this._roles);
return this._isOwner;
}
isPatient() {
this._isPatient = this._isPatient || hasRole(PATIENT, this._roles);
return this._isPatient;
}
isPhysician() {
this._isPhysician = this._isPhysician || hasRole(PHYSICIAN, this._roles);
return this._isPhysician;
}
isProvider() {
return this.isPhysician();
}
isStaff() {
return this.isManager() || this.isOwner();
}
}
export default User;
import user from './models/User';
export function userReducer(state = intialReducer, action) {
switch(action.type){
case USER_CREATE_SUCESS:
return {...state, user: new User(action.userInfo)}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment