src/helpers/Location.js
import LocationModel from '../models/Location';
import Helper from './Helper';
import { aggregate } from '../utilities/ClassUtility';
import { serviceFactory } from '../utilities/factories/ServiceFactory';
/**
* Helper class representing a location object. Location must have, at a minimum, one of the
* following:
* - latitude and longitude OR
* - country, state, ZIP code, city, and address
*/
class Location extends aggregate(LocationModel, Helper) {
/**
* Constructor for helper class representing a Location
*
* @param {Object} json - json api response from server
*/
constructor(json = {}) {
super(json);
this.deserializeRelationshipStubs(json);
this.syncRelationships(json);
}
/** @type {String} - The type */
static get type() {
return 'locations';
}
/** @type {Object} */
get localizable() {
return this._relationships.localizable;
}
/** @type {Object} */
set localizable(localizable) {
/** @type {Object} */
this._relationships.localizable = localizable;
}
/**
* @override
* Overrides the existing toJSON to adjust for address attributes
*/
toJSON() {
const obj = super.toJSON();
const attributes = {};
Object.keys(obj.attributes).forEach((key) => {
const value = obj.attributes[key];
const index = key.search(/\d/);
if (index > 0) {
key = `${key.substr(0, index)}_${key.substr(index)}`;
}
attributes[key] = value;
});
obj.attributes = attributes;
return obj;
}
/**
* Saves a location (insert if id doesn't exist, update if it does)
* @return {Promise<Location>} - Returns a promise via ajax call.
*
* @example
* import { Location, clinical6 } from 'clinical6';
*
* // Inserts new role (no existing id)
* const location = new Location({
* "title": "Test Location",
* "address_line_1": "New Hospital",
* "address_line_3": "Unit #59",
* "city": "Poway",
* "state": "CA",
* "country": "USA",
* "zip_code": "92064"
* });
* location.save();
*
* // Updates existing location(has existing id)
* clinical6.get(Location).then(locations => locations[0].save());
*/
async save() {
const service = serviceFactory.get(this.type);
return (this.id) ? service.update(this) : service.insert(this);
}
}
export default Location;